Spring Kafka monitoring: metrics, lag and observation

A Kafka consumer can fall behind, retry the same record for minutes or stop entirely without a single failed request to show for it. Monitoring is how you notice. This page explains what to measure, then runs each source of data against a real broker inside the program: client metrics, observation timers, consumer lag, container events and your own counters.

Contents

What to watch in a Kafka application

A web service shows trouble quickly: requests fail or slow down. A Kafka consumer fails quietly. If it slows down, records pile up in the topic; if it retries one record for minutes, its whole partition waits; if its thread dies, nothing happens at all. None of these produce an error response, so they must be found by measuring.

Four kinds of data cover most problems:

  • Consumer lag: how many records the group has not processed yet, per partition. It is the most important Kafka metric, because it rises whenever consumers fall behind, for whatever reason.
  • Client metrics: the Kafka producer and consumer each track hundreds of values, such as records sent, errors, batch sizes, fetch rates and request latency. Spring Boot publishes them to Micrometer.
  • Processing time: how long sends and listener calls take, from Micrometer observations that Spring for Apache Kafka can record.
  • Application events and business metrics: container start, stop and idle events, plus your own counters, such as records sent to a dead letter topic.
Monitoring sources in a Spring Boot Kafka application
SourceTurned on byAnswers
Kafka client metrics (kafka.producer.*, kafka.consumer.*)A MeterRegistry bean, for example from spring-boot-starter-actuatorThroughput, errors, lag as seen by the consumer
Observation timers (spring.kafka.template, spring.kafka.listener)spring.kafka.template.observation-enabled, spring.kafka.listener.observation-enabledTime per send and per record processed, plus tracing
Committed offsets and end offsetsThe Kafka Admin client, or external toolsConsumer lag per group and partition
Container eventsAn @EventListener; idle and non-responsive checks by propertyWhether consumers run, idle or hang
Custom metersYour code, with MeterRegistryBusiness outcomes, retries, dead letters

The programs are Spring Boot 4.1 applications with spring-boot-starter-kafka and spring-boot-starter-actuator. Each starts a single Kafka broker inside the JVM with EmbeddedKafkaKraftBroker from spring-kafka-test, in the startBroker method at the end. With no monitoring system configured, Boot uses an in-memory SimpleMeterRegistry, which the programs read directly.

Kafka client metrics in Micrometer

With a MeterRegistry present, Spring Boot adds Micrometer listeners to its producer and consumer factories, and every Kafka client metric becomes a meter. This program sends 50 click events, consumes them, then reads a few of the meters:

Java
package demo.kafka.metrics;

import ch.qos.logback.classic.Level;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.MeterRegistry;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Map;
import java.util.TreeSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.kafka.clients.admin.NewTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.config.TopicBuilder;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
import org.springframework.stereotype.Component;

@SpringBootApplication
public class ClientMetrics {

    static final CountDownLatch DONE = new CountDownLatch(50);

    @Bean
    NewTopic clicks() {
        return TopicBuilder.name("clicks").partitions(1).replicas(1).build();
    }

    @Component
    static class ClickListener {
        @KafkaListener(id = "clicks", topics = "clicks", groupId = "analytics")
        void on(String click) {
            DONE.countDown();
        }
    }

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        SpringApplication app = new SpringApplication(ClientMetrics.class);
        app.setDefaultProperties(Map.of(
                "spring.kafka.bootstrap-servers", broker.getBrokersAsString(),
                "spring.kafka.consumer.auto-offset-reset", "earliest",
                "spring.main.banner-mode", "off", "logging.level.root", "OFF"));
        try (var context = app.run(args)) {
            @SuppressWarnings("unchecked")
            KafkaTemplate<String, String> template = context.getBean(KafkaTemplate.class);
            for (int i = 0; i < 50; i++) {
                template.send("clicks", "page-" + i % 5, "click " + i);
            }
            template.flush();
            DONE.await(30, TimeUnit.SECONDS);
            Thread.sleep(1000); // let the clients update their metrics

            MeterRegistry registry = context.getBean(MeterRegistry.class);
            TreeSet<String> names = new TreeSet<>();
            for (Meter meter : registry.getMeters()) {
                if (meter.getId().getName().startsWith("kafka.")) {
                    names.add(meter.getId().getName());
                }
            }
            System.out.println("Kafka client meters registered: " + names.size()
                    + " (producer " + names.stream().filter(n -> n.startsWith("kafka.producer"))
                            .count() + ", consumer " + names.stream()
                            .filter(n -> n.startsWith("kafka.consumer")).count() + ")");
            print(registry, "kafka.producer.record.send.total");
            print(registry, "kafka.producer.record.error.total");
            print(registry, "kafka.consumer.fetch.manager.records.consumed.total");
            print(registry, "kafka.consumer.fetch.manager.records.lag.max");
            Meter sample = registry.find("kafka.producer.record.send.total").meter();
            System.out.println("tags on a producer meter: " + sample.getId().getTags().stream()
                    .map(t -> t.getKey()).sorted().toList());
        } finally {
            broker.destroy();
        }
    }

    static void print(MeterRegistry registry, String name) {
        // the consumer has one meter per client and one per topic; take the client-wide one
        Meter meter = registry.find(name).meters().stream()
                .filter(m -> m.getId().getTag("topic") == null).findFirst().orElseThrow();
        double value = meter.measure().iterator().next().getValue();
        System.out.println("  " + name + " = " + Math.round(value));
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO, and prints its storage setup, before Spring Boot
        // configures logging, so both are silenced while it starts.
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.ERROR);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
Kafka client meters registered: 166 (producer 77, consumer 88)
  kafka.producer.record.send.total = 50
  kafka.producer.record.error.total = 0
  kafka.consumer.fetch.manager.records.consumed.total = 50
  kafka.consumer.fetch.manager.records.lag.max = 0
tags on a producer meter: [client.id, kafka.version, spring.id]
  • One producer and one consumer registered well over a hundred meters between them. Kafka's own metric names are converted to Micrometer style, for example record-send-total in the producer-metrics group became kafka.producer.record.send.total.
  • kafka.producer.record.send.total counted the 50 records sent, and kafka.producer.record.error.total stayed at 0.
  • kafka.consumer.fetch.manager.records.consumed.total counted the same 50 on the consumer side.
  • records.lag.max was 0: once the consumer had caught up, its latest fetch was at the end of the partition.
  • Each meter is tagged with client.id, kafka.version and spring.id, so the meters of several producers and consumers in one application can be told apart.

The consumer registers some meters twice, once for the whole client and once per topic with a topic tag, which is why the program picks the meter without that tag. The consumer's own lag metric is useful, but only while the consumer runs: a consumer that has crashed reports nothing, so lag should also be measured from outside, as the lag section below does.

Observation timers for sends and listeners

Client metrics count records, but they do not say how long your own listener code takes. With observation enabled, Spring for Apache Kafka wraps every send and every listener call in a Micrometer observation, which produces a timer and, with a tracing bridge on the classpath, a trace span. The listener below spends 20 ms per payment:

Java
package demo.kafka.observation;

import ch.qos.logback.classic.Level;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.kafka.clients.admin.NewTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.config.TopicBuilder;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
import org.springframework.stereotype.Component;

@SpringBootApplication
public class ObservationTimers {

    static final CountDownLatch DONE = new CountDownLatch(20);

    @Bean
    NewTopic payments() {
        return TopicBuilder.name("payments").partitions(1).replicas(1).build();
    }

    @Component
    static class PaymentListener {
        @KafkaListener(id = "payments", topics = "payments", groupId = "ledger")
        void on(String payment) throws InterruptedException {
            Thread.sleep(20); // the work the timer measures
            DONE.countDown();
        }
    }

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        SpringApplication app = new SpringApplication(ObservationTimers.class);
        app.setDefaultProperties(Map.of(
                "spring.kafka.bootstrap-servers", broker.getBrokersAsString(),
                "spring.kafka.consumer.auto-offset-reset", "earliest",
                "spring.kafka.template.observation-enabled", "true",
                "spring.kafka.listener.observation-enabled", "true",
                "spring.main.banner-mode", "off", "logging.level.root", "OFF"));
        try (var context = app.run(args)) {
            @SuppressWarnings("unchecked")
            KafkaTemplate<String, String> template = context.getBean(KafkaTemplate.class);
            for (int i = 0; i < 20; i++) {
                template.send("payments", "payment " + i).get();
            }
            DONE.await(30, TimeUnit.SECONDS);
            Thread.sleep(500);

            MeterRegistry registry = context.getBean(MeterRegistry.class);
            for (String name : new String[] {"spring.kafka.template", "spring.kafka.listener"}) {
                Timer timer = registry.find(name).timer();
                System.out.println(name + ": count " + timer.count() + ", mean at least 20 ms: "
                        + (timer.mean(TimeUnit.MILLISECONDS) >= 20));
                timer.getId().getTags().stream()
                        .filter(t -> !t.getKey().equals("spring.kafka.listener.id"))
                        .forEach(t -> System.out.println("  tag " + t.getKey() + " = "
                                + t.getValue()));
            }
        } finally {
            broker.destroy();
        }
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO, and prints its storage setup, before Spring Boot
        // configures logging, so both are silenced while it starts.
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.ERROR);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
spring.kafka.template: count 20, mean at least 20 ms: true
  tag error = none
  tag messaging.destination.kind = topic
  tag messaging.destination.name = payments
  tag messaging.operation = publish
  tag messaging.system = kafka
  tag spring.kafka.template.name = kafkaTemplate
spring.kafka.listener: count 20, mean at least 20 ms: true
  tag error = none
  tag messaging.kafka.consumer.group = ledger
  tag messaging.operation = process
  tag messaging.source.kind = topic
  tag messaging.source.name = payments
  tag messaging.system = kafka
  • The spring.kafka.template timer counted the 20 sends, tagged with the topic, the operation publish and the template bean name.
  • The spring.kafka.listener timer counted the 20 listener calls, tagged with the consumer group ledger, the topic and the operation process. Its mean was at least the 20 ms that each call slept.
  • Both have an error tag, none here. A failing listener records its calls under the exception's class name, so failures and their duration can be graphed separately.

The program checks the mean against 20 ms instead of printing it, because real durations vary from run to run. The observation also carries trace context in record headers, so with Micrometer Tracing a request can be followed from the producer to the listener; that part is not shown here.

Measuring consumer lag

Lag is the difference between the newest offset in a partition and the offset the consumer group has committed. Measured from outside, with the Admin client, it keeps working when the consumer itself is down. This program processes 10 events, then pauses the listener container to stand in for a stuck consumer, sends 25 more, and resumes:

Java
package demo.kafka.lag;

import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.ListOffsetsResult.ListOffsetsResultInfo;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.admin.OffsetSpec;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.common.TopicPartition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.config.KafkaListenerEndpointRegistry;
import org.springframework.kafka.config.TopicBuilder;
import org.springframework.kafka.core.KafkaAdmin;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.listener.MessageListenerContainer;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
import org.springframework.stereotype.Component;

@SpringBootApplication
public class ConsumerLag {

    static volatile CountDownLatch processed = new CountDownLatch(10);

    @Bean
    NewTopic events() {
        return TopicBuilder.name("events").partitions(1).replicas(1).build();
    }

    @Component
    static class EventListener {
        @KafkaListener(id = "events", topics = "events", groupId = "reporting")
        void on(String event) {
            processed.countDown();
        }
    }

    // lag = newest offset in the partition - offset the group has committed
    static long lag(Admin admin) throws Exception {
        TopicPartition tp = new TopicPartition("events", 0);
        Map<TopicPartition, OffsetAndMetadata> committed = admin
                .listConsumerGroupOffsets("reporting").partitionsToOffsetAndMetadata().get();
        Map<TopicPartition, ListOffsetsResultInfo> end = admin
                .listOffsets(Map.of(tp, OffsetSpec.latest())).all().get();
        return end.get(tp).offset() - committed.get(tp).offset();
    }

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        SpringApplication app = new SpringApplication(ConsumerLag.class);
        app.setDefaultProperties(Map.of(
                "spring.kafka.bootstrap-servers", broker.getBrokersAsString(),
                "spring.kafka.consumer.auto-offset-reset", "earliest",
                "spring.main.banner-mode", "off", "logging.level.root", "OFF"));
        try (var context = app.run(args);
             Admin admin = Admin.create(
                     context.getBean(KafkaAdmin.class).getConfigurationProperties())) {
            @SuppressWarnings("unchecked")
            KafkaTemplate<String, String> template = context.getBean(KafkaTemplate.class);
            MessageListenerContainer container = context
                    .getBean(KafkaListenerEndpointRegistry.class).getListenerContainer("events");

            send(template, 0, 10);
            processed.await(30, TimeUnit.SECONDS);
            Thread.sleep(500); // let the container commit
            System.out.println("10 sent and processed        -> lag " + lag(admin));

            container.pause(); // stands in for a consumer that is stuck or too slow
            Thread.sleep(500);
            send(template, 10, 25);
            System.out.println("25 more sent, consumer paused -> lag " + lag(admin));

            processed = new CountDownLatch(25);
            container.resume();
            processed.await(30, TimeUnit.SECONDS);
            Thread.sleep(500);
            System.out.println("consumer resumed and caught up -> lag " + lag(admin));
        } finally {
            broker.destroy();
        }
    }

    static void send(KafkaTemplate<String, String> template, int from, int count)
            throws Exception {
        for (int i = from; i < from + count; i++) {
            template.send("events", "event " + i).get();
        }
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO, and prints its storage setup, before Spring Boot
        // configures logging, so both are silenced while it starts.
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.ERROR);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
10 sent and processed        -> lag 0
25 more sent, consumer paused -> lag 25
consumer resumed and caught up -> lag 0
  • After the first 10 events were processed and committed, the end offset and the committed offset were both 10, so the lag was 0.
  • While the container was paused, 25 more events arrived and nothing was committed: the lag rose to exactly 25.
  • After resume(), the listener worked through the backlog and the lag returned to 0.

In production, lag is usually collected by a separate tool, such as Kafka's own kafka-consumer-groups.sh --describe, a Kafka exporter for Prometheus, or the monitoring of a managed Kafka service, because a tool outside the application still reports when the application is down. Alert on lag that keeps growing over several minutes rather than on a single high value, since a burst of traffic also raises lag briefly.

Container events: started, idle, paused, stopped

Listener containers publish Spring application events when their consumer starts, stops, pauses or has received nothing for a while. This program has a listener on a topic that never gets a record, with the idle event interval set to 1 second, then pauses, resumes and stops the container:

Java
package demo.kafka.events;

import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.kafka.clients.admin.NewTopic;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.EventListener;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.config.KafkaListenerEndpointRegistry;
import org.springframework.kafka.config.TopicBuilder;
import org.springframework.kafka.event.KafkaEvent;
import org.springframework.kafka.event.ListenerContainerIdleEvent;
import org.springframework.kafka.listener.MessageListenerContainer;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
import org.springframework.stereotype.Component;

@SpringBootApplication
public class ContainerEvents {

    static final List<String> EVENTS = new CopyOnWriteArrayList<>();

    @Bean
    NewTopic audit() {
        return TopicBuilder.name("audit").partitions(1).replicas(1).build();
    }

    @Component
    static class Listeners {
        @KafkaListener(id = "audit", topics = "audit", groupId = "audit")
        void on(String entry) {
        }

        @EventListener
        void onKafkaEvent(KafkaEvent event) {
            String name = event.getClass().getSimpleName();
            if (event instanceof ListenerContainerIdleEvent idle) {
                name += " (idle for at least 1 s: " + (idle.getIdleTime() >= 1000) + ")";
            }
            if (!EVENTS.contains(name)) {
                EVENTS.add(name);
            }
        }
    }

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        SpringApplication app = new SpringApplication(ContainerEvents.class);
        app.setDefaultProperties(Map.of(
                "spring.kafka.bootstrap-servers", broker.getBrokersAsString(),
                "spring.kafka.listener.idle-event-interval", "1s",
                "spring.kafka.listener.poll-timeout", "500ms",
                "spring.main.banner-mode", "off", "logging.level.root", "OFF"));
        try (var context = app.run(args)) {
            MessageListenerContainer container = context
                    .getBean(KafkaListenerEndpointRegistry.class).getListenerContainer("audit");
            Thread.sleep(3000); // no records arrive
            System.out.println("running: " + container.isRunning()
                    + ", assigned partitions: " + container.getAssignedPartitions());
            container.pause();
            Thread.sleep(1500);
            System.out.println("pause requested: " + container.isPauseRequested()
                    + ", paused: " + container.isContainerPaused());
            container.resume();
            Thread.sleep(1500);
            container.stop();
            Thread.sleep(500);
            System.out.println("events seen, in order of first appearance:");
            EVENTS.forEach(e -> System.out.println("  " + e));
        } finally {
            broker.destroy();
        }
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO, and prints its storage setup, before Spring Boot
        // configures logging, so both are silenced while it starts.
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.ERROR);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
running: true, assigned partitions: [audit-0]
pause requested: true, paused: true
events seen, in order of first appearance:
  ConsumerStartingEvent
  ConsumerStartedEvent
  ConsumerPausedEvent
  ConsumerResumedEvent
  ListenerContainerIdleEvent (idle for at least 1 s: true)
  ContainerStoppedEvent
  ConsumerStoppingEvent
  ConsumerStoppedEvent
  ConcurrentContainerStoppedEvent
  • While running, the container owned partition audit-0, and pause() set both the pause request and, a moment later, the paused state of the consumer.
  • The events arrived in lifecycle order: the consumer starting and started, paused and resumed, and finally the stop events of the consumer, of the container and of its parent concurrent container.
  • The first ListenerContainerIdleEvent was published after the resume, once the consumer had polled for more than a second without records. Idle events repeat every interval while nothing arrives; the program prints each event type once.
  • ListenerContainerIdleEvent needs spring.kafka.listener.idle-event-interval. The poll timeout is lowered to 500 ms, because the container checks for idleness after each poll returns, and the default poll timeout is 5 seconds.

An idle event on a topic that should be busy means producers have stopped. For consumers that hang inside the listener, set spring.kafka.listener.monitor-interval and no-poll-threshold: the container then publishes a NonResponsiveConsumerEvent when its consumer has not polled for that long. The KafkaListenerEndpointRegistry, used here, also lets a health check or an admin endpoint ask each container whether it is running.

Custom metrics for business outcomes

Kafka's metrics know about records, not about orders. Counting what the application did, and what it gave up on, makes a dashboard meaningful. This fulfilment listener counts processed orders per country and times every attempt, while the error handler counts failed deliveries and orders sent to the recoverer. One of the ten orders is invalid:

Java
package demo.kafka.custom;

import ch.qos.logback.classic.Level;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.kafka.clients.admin.NewTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.config.TopicBuilder;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.listener.CommonErrorHandler;
import org.springframework.kafka.listener.DefaultErrorHandler;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
import org.springframework.stereotype.Component;
import org.springframework.util.backoff.FixedBackOff;

@SpringBootApplication
public class CustomMetrics {

    static final CountDownLatch DONE = new CountDownLatch(10);

    @Bean
    NewTopic orders() {
        return TopicBuilder.name("orders").partitions(1).replicas(1).build();
    }

    @Bean
    CommonErrorHandler errorHandler(MeterRegistry registry) {
        Counter recovered = Counter.builder("orders.recovered")
                .description("orders given up on after all retries").register(registry);
        DefaultErrorHandler handler = new DefaultErrorHandler((record, e) -> {
            recovered.increment();
            DONE.countDown();
        }, new FixedBackOff(0, 2));
        handler.setRetryListeners((record, e, attempt) ->
                registry.counter("orders.delivery.failures").increment());
        return handler;
    }

    @Component
    static class OrderListener {
        private final MeterRegistry registry;
        private final Timer timer;

        OrderListener(MeterRegistry registry) {
            this.registry = registry;
            this.timer = Timer.builder("orders.processing").register(registry);
        }

        @KafkaListener(id = "orders", topics = "orders", groupId = "fulfilment")
        void on(String order) {
            timer.record(() -> {
                String country = order.substring(0, 2);
                if (order.endsWith("invalid")) {
                    throw new IllegalArgumentException("invalid order " + order);
                }
                registry.counter("orders.processed", "country", country).increment();
            });
            DONE.countDown();
        }
    }

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        SpringApplication app = new SpringApplication(CustomMetrics.class);
        app.setDefaultProperties(Map.of(
                "spring.kafka.bootstrap-servers", broker.getBrokersAsString(),
                "spring.kafka.consumer.auto-offset-reset", "earliest",
                "spring.main.banner-mode", "off", "logging.level.root", "OFF"));
        try (var context = app.run(args)) {
            @SuppressWarnings("unchecked")
            KafkaTemplate<String, String> template = context.getBean(KafkaTemplate.class);
            String[] orders = {"DE-1", "FR-2", "DE-3", "DE-4 invalid", "FR-5", "DE-6", "DE-7",
                    "FR-8", "DE-9", "FR-10"};
            for (String order : orders) {
                template.send("orders", order).get();
            }
            DONE.await(30, TimeUnit.SECONDS);

            MeterRegistry registry = context.getBean(MeterRegistry.class);
            System.out.println("orders.processed{country=DE}: "
                    + registry.get("orders.processed").tag("country", "DE").counter().count());
            System.out.println("orders.processed{country=FR}: "
                    + registry.get("orders.processed").tag("country", "FR").counter().count());
            System.out.println("orders.delivery.failures    : "
                    + registry.get("orders.delivery.failures").counter().count());
            System.out.println("orders.recovered            : "
                    + registry.get("orders.recovered").counter().count());
            System.out.println("orders.processing timer count: "
                    + registry.get("orders.processing").timer().count());
        } finally {
            broker.destroy();
        }
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO, and prints its storage setup, before Spring Boot
        // configures logging, so both are silenced while it starts.
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.ERROR);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
orders.processed{country=DE}: 5.0
orders.processed{country=FR}: 4.0
orders.delivery.failures    : 3.0
orders.recovered            : 1.0
orders.processing timer count: 12
  • Nine orders were processed, 5 from DE and 4 from FR, counted by orders.processed with a country tag.
  • The invalid order failed three times, the first delivery and two retries of FixedBackOff(0, 2), so orders.delivery.failures is 3, counted by the retry listener.
  • After the last retry the recoverer gave up once: orders.recovered is 1. In a real application this is the number to alert on.
  • The orders.processing timer counted 12 calls: 9 successful ones plus the 3 failed attempts, because Timer.record also measures calls that throw.

Keep tag values to a small, fixed set, such as country codes or outcome names. A tag with an order id or a customer id creates a new time series per value and can overload the monitoring system.

Exporting to Prometheus and Grafana

The programs above read the in-memory registry. To scrape the same meters with Prometheus, add io.micrometer:micrometer-registry-prometheus and expose the actuator endpoint. That registry is not on this page's classpath, so the configuration below was not run; it follows the Spring Boot actuator documentation:

Properties
# application.properties
management.endpoints.web.exposure.include=health,prometheus
management.metrics.tags.application=order-service
spring.kafka.listener.observation-enabled=true
spring.kafka.template.observation-enabled=true

Prometheus then scrapes /actuator/prometheus, where dots in meter names become underscores, for example kafka_consumer_fetch_manager_records_lag_max, and timers gain _seconds_count and _seconds_sum series. Useful panels and alerts are the lag per partition from a Kafka exporter, the rate of orders_recovered_total, and listener time from spring_kafka_listener_seconds. Spring Boot has no Kafka health indicator, so a broker outage does not change /actuator/health on its own; lag and container events are the better signals.

Choosing what to monitor

Questions and the signal that answers them
QuestionSignal
Are consumers keeping up?Consumer lag per partition, measured outside the application
Are producers failing?kafka.producer.record.error.total and failed send futures
Is the listener code slow?The spring.kafka.listener observation timer
Is a consumer stuck or stopped?NonResponsiveConsumerEvent, container stop events, lag that only grows
Has traffic stopped?ListenerContainerIdleEvent, or a falling consume rate
Are records being given up on?A counter in the recoverer, and growth of the dead letter topic

The settings that cause most monitoring alerts are covered on the other Kafka pages: error handling and retries, dead letter topics, @KafkaListener and KafkaTemplate. For actuator itself, see Spring Boot Actuator, and for tracing across services, observability.