Kafka monitoring: what to watch and where it comes from

Kafka exposes thousands of metrics, and a handful of them tell you whether the cluster is healthy and whether clients keep up. This page explains where the metrics come from, then runs brokers and clients inside each program to read broker MBeans, take brokers down and watch the health checks react, and read producer and consumer metrics directly, through Micrometer, and as a Prometheus scrape.

Share

Contents

Where Kafka metrics come from

Every Kafka process measures itself. Brokers and controllers count messages, bytes and requests, time every request type, and track the state of every partition they host. Producers, consumers, Admin clients, Connect workers and Streams applications keep their own metrics in the client library. All of them are published through JMX, Java's built-in management interface, as MBeans that any JMX tool can read.

There are two metric libraries underneath. Broker metrics such as kafka.server:type=BrokerTopicMetrics,name=MessagesInPerSec use the Yammer library: counters with a total Count and moving rates, and timers with percentiles. Client metrics, and some newer broker metrics, use Kafka's own org.apache.kafka.common.metrics library, where each metric has a name, a group and tags, such as record-send-total in the group producer-metrics with the tag client-id. The JmxReporter, on by default through metric.reporters, turns these into MBeans too.

Monitoring systems usually do not read JMX themselves. A Prometheus JMX exporter agent on each broker, or Micrometer inside an application, converts the MBeans or client metrics into the monitoring system's format. Whatever the transport, the same few metrics matter:

The metrics that matter most
MetricWhereHealthy valueShows
UnderReplicatedPartitionsEach broker0Followers that fell behind or brokers that are down
UnderMinIsrPartitionCountEach broker0Partitions that reject acks=all writes
OfflinePartitionsCountActive controller0Partitions with no leader: no reads or writes
ActiveControllerCountControllers1 in totalWhether the KRaft quorum has a leader
RequestHandlerAvgIdlePercent, NetworkProcessorAvgIdlePercentEach brokerWell above 0.3Broker threads running out of capacity
TotalTimeMs per request typeEach brokerStable percentilesSlow produce or fetch handling
record-error-total, record-retry-totalProducers0, or flatFailed or retried sends
records-lag-max and committed-offset lagConsumers, groupsSmall and not growingConsumers falling behind

The programs start brokers inside the JVM, so they can read the broker's MBeans from the same MBeanServer as their own. Single-broker programs use EmbeddedKafkaKraftBroker from spring-kafka-test; the cluster program uses KafkaClusterTestKit, the Kafka 4.2.2 test cluster it is built on, with three brokers. A real cluster runs each broker in its own JVM, usually on its own machine.

Broker metrics over JMX

The program writes 1,000 records of about 100 bytes to a two-partition topic, reads them back with a consumer group, and then reads the broker's MBeans by name:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.management.ManagementFactory;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;

public class BrokerJmx {

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        String bootstrap = broker.getBrokersAsString();
        try (Admin admin = Admin.create(Map.<String, Object>of("bootstrap.servers", bootstrap))) {
            admin.createTopics(List.of(new NewTopic("orders", 2, (short) 1))).all().get();
        }
        try (KafkaProducer<String, String> producer = new KafkaProducer<>(
                Map.of("bootstrap.servers", bootstrap),
                new StringSerializer(), new StringSerializer())) {
            for (int i = 0; i < 1000; i++) {
                producer.send(new ProducerRecord<>("orders", "key-" + i, "x".repeat(100)));
            }
        }
        try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(Map.of(
                "bootstrap.servers", bootstrap, "group.id", "reports",
                "auto.offset.reset", "earliest"),
                new StringDeserializer(), new StringDeserializer())) {
            consumer.subscribe(List.of("orders"));
            int read = 0;
            while (read < 1000) {
                read += consumer.poll(Duration.ofMillis(500)).count();
            }
        }

        MBeanServer jmx = ManagementFactory.getPlatformMBeanServer();
        TreeSet<String> domains = new TreeSet<>(List.of(jmx.getDomains()));
        domains.removeIf(d -> !d.startsWith("kafka"));
        System.out.println("Kafka JMX domains: " + domains);

        String topicMetrics = "kafka.server:type=BrokerTopicMetrics,topic=orders,name=";
        print(jmx, topicMetrics + "MessagesInPerSec", "Count");
        print(jmx, topicMetrics + "BytesInPerSec", "Count");
        print(jmx, topicMetrics + "BytesOutPerSec", "Count");
        print(jmx, "kafka.server:type=BrokerTopicMetrics,name=MessagesInPerSec", "Count");
        print(jmx, "kafka.server:type=ReplicaManager,name=UnderReplicatedPartitions", "Value");
        print(jmx, "kafka.server:type=ReplicaManager,name=UnderMinIsrPartitionCount", "Value");
        print(jmx, "kafka.server:type=ReplicaManager,name=PartitionCount", "Value");
        print(jmx, "kafka.controller:type=KafkaController,name=ActiveControllerCount", "Value");
        print(jmx, "kafka.controller:type=KafkaController,name=OfflinePartitionsCount", "Value");
        print(jmx, "kafka.network:type=RequestMetrics,name=RequestsPerSec,request=Produce,"
                + "version=" + produceVersion(jmx), "Count");
        ObjectName produceTime = new ObjectName(
                "kafka.network:type=RequestMetrics,name=TotalTimeMs,request=Produce");
        System.out.println("Produce TotalTimeMs attributes: "
                + List.of(jmx.getMBeanInfo(produceTime).getAttributes()).stream()
                        .map(a -> a.getName()).toList());
        broker.destroy();
    }

    // the request counter has one MBean per request version; this finds the one used
    static String produceVersion(MBeanServer jmx) throws Exception {
        return jmx.queryNames(new ObjectName("kafka.network:type=RequestMetrics,"
                + "name=RequestsPerSec,request=Produce,*"), null).iterator().next()
                .getKeyProperty("version");
    }

    static void print(MBeanServer jmx, String name, String attribute) throws Exception {
        Object value = jmx.getAttribute(new ObjectName(name), attribute);
        System.out.printf("%-62s %s%n", name.substring(name.indexOf(':') + 1), value);
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // 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 {
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1);
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
Kafka JMX domains: [kafka, kafka.cluster, kafka.controller, kafka.coordinator.group, kafka.coordinator.transaction, kafka.log, kafka.network, kafka.server, kafka.utils]
type=BrokerTopicMetrics,topic=orders,name=MessagesInPerSec     1000
type=BrokerTopicMetrics,topic=orders,name=BytesInPerSec        116866
type=BrokerTopicMetrics,topic=orders,name=BytesOutPerSec       116866
type=BrokerTopicMetrics,name=MessagesInPerSec                  1005
type=ReplicaManager,name=UnderReplicatedPartitions             0
type=ReplicaManager,name=UnderMinIsrPartitionCount             0
type=ReplicaManager,name=PartitionCount                        52
type=KafkaController,name=ActiveControllerCount                1
type=KafkaController,name=OfflinePartitionsCount               0
type=RequestMetrics,name=RequestsPerSec,request=Produce,version=13 4
Produce TotalTimeMs attributes: [50thPercentile, Mean, StdDev, 75thPercentile, 95thPercentile, 98thPercentile, 99thPercentile, 999thPercentile, Count, Min, Max]
  • The broker registers MBeans in several kafka.* domains: kafka.server for request handling and replication, kafka.network for requests, kafka.log for log segments, kafka.controller for the controller, and the coordinators for groups and transactions.
  • The per-topic MessagesInPerSec counted exactly 1,000 messages for orders. Despite the name, the MBean has a running total in Count; the rates are in OneMinuteRate and similar attributes.
  • The broker-wide MessagesInPerSec is a little higher than 1,000. The extra messages are the consumer group's offset commits, which are records in __consumer_offsets.
  • BytesInPerSec and BytesOutPerSec count bytes of record batches, including batch headers, so they depend on how the producer batched. Here the consumer read everything once, so the two match.
  • PartitionCount includes the 50 partitions of __consumer_offsets, created when the group first committed.
  • With one broker, there is nothing to replicate: UnderReplicatedPartitions and UnderMinIsrPartitionCount are 0, ActiveControllerCount is 1 because this node is also the controller, and no partition is offline.
  • Request metrics are tagged by request type and API version. TotalTimeMs is a histogram with percentiles; it splits further into RequestQueueTimeMs, LocalTimeMs, RemoteTimeMs and ResponseSendTimeMs, which show where a slow request spent its time.

The request count and the byte counts vary from run to run, because they depend on batching. To expose all of this to Prometheus, the usual setup starts each broker with the Prometheus JMX exporter as a Java agent, for example KAFKA_OPTS="-javaagent:/opt/jmx_prometheus_javaagent.jar=7071:/opt/kafka-rules.yml", with rules that map MBean names to metric names. That setup was not run here.

Cluster health when brokers fail

Replication metrics only mean something with several brokers. This program creates a topic with 3 replicas and min.insync.replicas=2 on three brokers, then stops brokers one at a time. After each step it runs the checks a monitoring job makes, and test writes with acks=all and acks=1:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.admin.TopicDescription;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.TopicPartitionInfo;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.common.test.KafkaClusterTestKit;
import org.apache.kafka.common.test.TestKitNodes;
import org.apache.kafka.metadata.bootstrap.BootstrapMetadata;
import org.apache.kafka.server.common.Feature;
import org.apache.kafka.server.common.MetadataVersion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ClusterHealth {

    public static void main(String[] args) throws Exception {
        KafkaClusterTestKit cluster = startCluster();
        String bootstrap = cluster.bootstrapServers();
        try (Admin admin = Admin.create(Map.<String, Object>of("bootstrap.servers", bootstrap))) {
            admin.createTopics(List.of(new NewTopic("payments", 3, (short) 3)
                    .configs(Map.of("min.insync.replicas", "2")))).all().get();
            check(admin, bootstrap, "all brokers up");

            stop(cluster, 2);
            check(admin, bootstrap, "broker 2 stopped");

            stop(cluster, 1);
            check(admin, bootstrap, "brokers 1 and 2 stopped");
        } finally {
            cluster.close();
        }
    }

    static void stop(KafkaClusterTestKit cluster, int id) {
        cluster.brokers().get(id).shutdown();
        cluster.brokers().get(id).awaitShutdown();
    }

    // the checks a monitoring job runs: replicas out of sync, partitions below
    // min.insync.replicas, partitions without a leader, and a test write per acks level
    static void check(Admin admin, String bootstrap, String label) throws Exception {
        Thread.sleep(1000); // the controller notices the change and updates the ISR
        TopicDescription d = admin.describeTopics(List.of("payments")).allTopicNames().get()
                .get("payments");
        int under = 0;
        int belowMinIsr = 0;
        int offline = 0;
        for (TopicPartitionInfo p : d.partitions()) {
            under += p.isr().size() < p.replicas().size() ? 1 : 0;
            belowMinIsr += p.isr().size() < 2 ? 1 : 0;
            offline += p.leader() == null ? 1 : 0;
        }
        System.out.println(label + ": under-replicated " + under + ", under min ISR "
                + belowMinIsr + ", offline " + offline + ", ISR sizes "
                + d.partitions().stream().map(p -> p.isr().size()).toList());
        for (String acks : List.of("all", "1")) {
            System.out.println("  acks=" + acks + ": " + write(bootstrap, acks));
        }
    }

    static String write(String bootstrap, String acks) {
        Map<String, Object> props = new HashMap<>(Map.of("bootstrap.servers", bootstrap,
                "acks", acks, "delivery.timeout.ms", "3000", "request.timeout.ms", "2000",
                "linger.ms", "0"));
        if (!acks.equals("all")) {
            props.put("enable.idempotence", "false"); // idempotence requires acks=all
        }
        try (KafkaProducer<String, String> producer = new KafkaProducer<>(props,
                new StringSerializer(), new StringSerializer())) {
            int ok = 0;
            String error = "";
            for (int partition = 0; partition < 3; partition++) {
                try {
                    producer.send(new ProducerRecord<>("payments", partition, null, "p")).get();
                    ok++;
                } catch (ExecutionException e) {
                    error = ", error " + e.getCause().getClass().getSimpleName();
                }
            }
            Object retries = producer.metrics().entrySet().stream()
                    .filter(e -> e.getKey().group().equals("producer-metrics")
                            && e.getKey().name().equals("record-retry-total"))
                    .findFirst().orElseThrow().getValue().metricValue();
            return ok + " of 3 partitions accepted the write" + error + ", record-retry-total "
                    + retries;
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
    }

    // Starts a KRaft cluster in this JVM with KafkaClusterTestKit, Kafka's own test
    // cluster (EmbeddedKafkaKraftBroker is built on it): one controller, three brokers
    static KafkaClusterTestKit startCluster() throws Exception {
        // 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.OFF);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // production metadata version and feature levels, as a new 4.2 cluster gets
            Map<String, Short> features = new HashMap<>();
            for (Feature f : Feature.PRODUCTION_FEATURES) {
                if (f != Feature.KRAFT_VERSION) {
                    features.put(f.featureName(), f.latestProduction());
                }
            }
            KafkaClusterTestKit cluster = new KafkaClusterTestKit.Builder(
                    new TestKitNodes.Builder()
                            .setCombined(false)
                            .setNumControllerNodes(1)
                            .setNumBrokerNodes(3)
                            .setBootstrapMetadata(BootstrapMetadata.fromVersions(
                                    MetadataVersion.latestProduction(), features, "demo"))
                            .build())
                    .build();
            cluster.format();
            cluster.startup();
            cluster.waitForReadyBrokers();
            return cluster;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
all brokers up: under-replicated 0, under min ISR 0, offline 0, ISR sizes [3, 3, 3]
  acks=all: 3 of 3 partitions accepted the write, record-retry-total 0.0
  acks=1: 3 of 3 partitions accepted the write, record-retry-total 0.0
broker 2 stopped: under-replicated 3, under min ISR 0, offline 0, ISR sizes [2, 2, 2]
  acks=all: 3 of 3 partitions accepted the write, record-retry-total 0.0
  acks=1: 3 of 3 partitions accepted the write, record-retry-total 0.0
brokers 1 and 2 stopped: under-replicated 3, under min ISR 3, offline 0, ISR sizes [1, 1, 1]
  acks=all: 0 of 3 partitions accepted the write, error TimeoutException, record-retry-total 18.0
  acks=1: 3 of 3 partitions accepted the write, record-retry-total 0.0
  • With all brokers up, every partition had 3 replicas in sync and both kinds of write succeeded.
  • With broker 2 stopped, all 3 partitions became under-replicated: their in-sync replica sets shrank to 2. Writes still succeeded, even with acks=all, because 2 replicas meet min.insync.replicas=2. The cluster is degraded but fully working, which is exactly when an alert on under-replicated partitions should fire: one more failure will cause errors.
  • With brokers 1 and 2 stopped, each partition had 1 replica in sync, below the minimum. No partition was offline, since broker 0 still led all three, so acks=1 writes kept working.
  • The acks=all writes failed. The broker answered NOT_ENOUGH_REPLICAS, which is retriable, so the producer retried until delivery.timeout.ms, 3 seconds here, ran out, and the send failed with TimeoutException. The producer's record-retry-total shows the retries that happened in that time.

This is the reason to monitor UnderMinIsrPartitionCount separately: it counts the partitions where durable writes are already failing, while UnderReplicatedPartitions warns earlier. It is also why acks=1 is risky: those writes succeeded on a single copy, and they are lost if broker 0 fails before the others return. The program computes the counts from describeTopics, which works from outside the brokers; kafka-topics.sh --describe --under-replicated-partitions and --under-min-isr-partitions do the same from a shell.

Producer and consumer metrics

Clients often show a problem before the brokers do: a producer that retries, a consumer that falls behind. The producer below sends 1,000 records with lz4 compression, and the consumer reads only part of the topic, so that it lags. The program prints a selection of the client metrics, then binds the consumer's metrics to Micrometer:

Java
import ch.qos.logback.classic.Level;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.binder.kafka.KafkaClientMetrics;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import java.io.OutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.Metric;
import org.apache.kafka.common.MetricName;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;

public class ClientMetrics {

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        String bootstrap = broker.getBrokersAsString();
        try (Admin admin = Admin.create(Map.<String, Object>of("bootstrap.servers", bootstrap))) {
            admin.createTopics(List.of(new NewTopic("orders", 1, (short) 1))).all().get();
        }
        try (KafkaProducer<String, String> producer = new KafkaProducer<>(Map.of(
                "bootstrap.servers", bootstrap, "client.id", "order-producer",
                "compression.type", "lz4"),
                new StringSerializer(), new StringSerializer());
                KafkaConsumer<String, String> consumer = new KafkaConsumer<>(Map.of(
                        "bootstrap.servers", bootstrap, "client.id", "order-consumer",
                        "group.id", "reports", "auto.offset.reset", "earliest",
                        "max.poll.records", "100"),
                        new StringDeserializer(), new StringDeserializer())) {
            for (int i = 0; i < 1000; i++) {
                producer.send(new ProducerRecord<>("orders", "key-" + i, "order " + i));
            }
            producer.flush();

            consumer.subscribe(List.of("orders"));
            int read = 0;
            while (read < 300) { // read only part of the topic, so the consumer lags
                read += consumer.poll(Duration.ofMillis(500)).count();
            }

            System.out.println("producer metrics (group producer-metrics):");
            show(producer.metrics(), "producer-metrics", "record-send-total",
                    "record-error-total", "record-retry-total", "batch-size-avg",
                    "records-per-request-avg", "compression-rate-avg", "request-latency-avg",
                    "buffer-available-bytes");
            System.out.println("consumer metrics (group consumer-fetch-manager-metrics):");
            show(consumer.metrics(), "consumer-fetch-manager-metrics",
                    "records-lag-max", "fetch-latency-avg");
            for (Map.Entry<MetricName, ? extends Metric> e : consumer.metrics().entrySet()) {
                if (e.getKey().name().equals("records-lag")) {
                    System.out.println("  records-lag " + e.getKey().tags() + " = "
                            + e.getValue().metricValue());
                }
            }

            // Micrometer turns the same metrics into meters, as Spring Boot does
            SimpleMeterRegistry registry = new SimpleMeterRegistry();
            try (KafkaClientMetrics binder = new KafkaClientMetrics(consumer)) {
                binder.bindTo(registry);
                Meter lag = registry.find("kafka.consumer.fetch.manager.records.lag").meter();
                System.out.println("Micrometer: " + registry.getMeters().size()
                        + " consumer meters, for example " + lag.getId().getName() + " "
                        + lag.getId().getTags());
            }
        } finally {
            broker.destroy();
        }
    }

    static void show(Map<MetricName, ? extends Metric> metrics, String group, String... names) {
        Map<String, Object> found = new TreeMap<>();
        for (Map.Entry<MetricName, ? extends Metric> e : metrics.entrySet()) {
            MetricName m = e.getKey();
            if (m.group().equals(group) && m.tags().size() == 1 // client-wide, not per topic
                    && List.of(names).contains(m.name())) {
                Object v = e.getValue().metricValue();
                found.put(m.name(), v instanceof Double d ? String.format("%.1f", d) : v);
            }
        }
        found.forEach((k, v) -> System.out.printf("  %-24s %s%n", k, v));
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // 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 {
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1);
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
producer metrics (group producer-metrics):
  batch-size-avg           1743.7
  buffer-available-bytes   33554432.0
  compression-rate-avg     0.7
  record-error-total       0.0
  record-retry-total       0.0
  record-send-total        1000.0
  records-per-request-avg  142.9
  request-latency-avg      88.0
consumer metrics (group consumer-fetch-manager-metrics):
  fetch-latency-avg        89.0
  records-lag-max          900.0
  records-lag {client-id=order-consumer, topic=orders, partition=0} = 700.0
Micrometer: 130 consumer meters, for example kafka.consumer.fetch.manager.records.lag [tag(client.id=order-consumer), tag(kafka.version=4.2.2), tag(partition=0), tag(topic=orders)]
  • record-send-total is 1000, and record-error-total and record-retry-total are 0: every record was sent at the first attempt. These are the producer metrics to alert on.
  • batch-size-avg and records-per-request-avg show how well the producer batched: well over a hundred records per request. compression-rate-avg is the compressed size divided by the original size, so lower is better.
  • buffer-available-bytes is the free part of the 32 MB buffer.memory. When it approaches 0, send() starts to block.
  • records-lag-max is the largest lag the consumer saw in the current time window, and records-lag is tagged per partition. The consumer computes them from the high watermark that each fetch response carries, so they only update while the consumer is fetching.
  • Micrometer's KafkaClientMetrics turned the consumer's metrics into well over a hundred meters, named like kafka.consumer.fetch.manager.records.lag, with the Kafka tags plus kafka.version. Spring Boot does this automatically for the clients it creates.

Latencies, averages and batch sizes change from run to run; the totals do not. A consumer that has stopped or crashed reports no lag at all, so lag must also be watched from outside, through committed offsets, as consumer lag monitoring shows.

Client metrics as a Prometheus scrape

Most teams collect client metrics with Prometheus. The program repeats the previous setup without compression, binds both clients with KafkaClientMetrics to a PrometheusMeterRegistry from micrometer-registry-prometheus 1.17.2, serves the registry at /metrics and fetches the page over HTTP, as the Prometheus server does. It prints a count of the metric families and the lines for the metrics from the alert table:

Java
import ch.qos.logback.classic.Level;
import com.sun.net.httpserver.HttpServer;
import io.micrometer.core.instrument.binder.kafka.KafkaClientMetrics;
import io.micrometer.prometheusmetrics.PrometheusConfig;
import io.micrometer.prometheusmetrics.PrometheusMeterRegistry;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;

public class ClientPrometheus {

    static final List<String> SHOWN = List.of("kafka_producer_record_send_total",
            "kafka_producer_record_error_total", "kafka_producer_record_retry_total",
            "kafka_producer_buffer_available_bytes",
            "kafka_consumer_fetch_manager_records_lag",
            "kafka_consumer_fetch_manager_records_lag_max");

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        String bootstrap = broker.getBrokersAsString();
        PrometheusMeterRegistry registry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
        registry.config().commonTags("application", "orders-service");
        HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
        server.createContext("/metrics", exchange -> {
            byte[] body = registry.scrape().getBytes(StandardCharsets.UTF_8);
            exchange.getResponseHeaders().set("Content-Type",
                    "text/plain; version=0.0.4; charset=utf-8");
            exchange.sendResponseHeaders(200, body.length);
            try (OutputStream out = exchange.getResponseBody()) {
                out.write(body);
            }
        });
        server.start();

        try (Admin admin = Admin.create(Map.<String, Object>of("bootstrap.servers", bootstrap))) {
            admin.createTopics(List.of(new NewTopic("orders", 1, (short) 1))).all().get();
        }
        try (KafkaProducer<String, String> producer = new KafkaProducer<>(Map.of(
                "bootstrap.servers", bootstrap, "client.id", "order-producer"),
                new StringSerializer(), new StringSerializer());
                KafkaConsumer<String, String> consumer = new KafkaConsumer<>(Map.of(
                        "bootstrap.servers", bootstrap, "client.id", "order-consumer",
                        "group.id", "reports", "auto.offset.reset", "earliest",
                        "max.poll.records", "100"),
                        new StringDeserializer(), new StringDeserializer());
                KafkaClientMetrics producerMetrics = new KafkaClientMetrics(producer);
                KafkaClientMetrics consumerMetrics = new KafkaClientMetrics(consumer)) {
            for (int i = 0; i < 1000; i++) {
                producer.send(new ProducerRecord<>("orders", "key-" + i, "order " + i));
            }
            producer.flush();
            consumer.subscribe(List.of("orders"));
            int read = 0;
            while (read < 300) { // read only part of the topic, so the consumer lags
                read += consumer.poll(Duration.ofMillis(500)).count();
            }
            // bound after the clients have worked, so that per-topic and
            // per-partition metrics already exist
            producerMetrics.bindTo(registry);
            consumerMetrics.bindTo(registry);

            HttpResponse<String> response = HttpClient.newHttpClient().send(
                    HttpRequest.newBuilder(URI.create("http://localhost:"
                            + server.getAddress().getPort() + "/metrics")).build(),
                    HttpResponse.BodyHandlers.ofString());
            List<String> lines = response.body().lines().toList();
            System.out.println("GET /metrics: " + response.statusCode() + ", "
                    + response.headers().firstValue("Content-Type").orElse(""));

            Map<String, Integer> families = new TreeMap<>();
            for (String line : lines) {
                if (line.startsWith("# TYPE ")) {
                    String type = line.substring(line.lastIndexOf(' ') + 1);
                    families.merge(line.split(" ")[2].startsWith("kafka_producer")
                            ? "producer " + type : "consumer " + type, 1, Integer::sum);
                }
            }
            System.out.println(lines.size() + " lines, metric families by client and type: "
                    + families);
            for (String line : lines) {
                for (String name : SHOWN) {
                    if (line.startsWith(name + "{") || line.equals("# TYPE " + name + " "
                            + line.substring(line.lastIndexOf(' ') + 1))) {
                        System.out.println(line);
                    }
                }
            }
        } finally {
            server.stop(0);
            broker.destroy();
        }
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // 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 {
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1);
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
GET /metrics: 200, text/plain; version=0.0.4; charset=utf-8
633 lines, metric families by client and type: {consumer counter=31, consumer gauge=75, producer counter=37, producer gauge=57}
# TYPE kafka_consumer_fetch_manager_records_lag gauge
kafka_consumer_fetch_manager_records_lag{application="orders-service",client_id="order-consumer",kafka_version="4.2.2",partition="0",topic="orders"} 700.0
# TYPE kafka_consumer_fetch_manager_records_lag_max gauge
kafka_consumer_fetch_manager_records_lag_max{application="orders-service",client_id="order-consumer",kafka_version="4.2.2",partition="0",topic="orders"} 900.0
# TYPE kafka_producer_buffer_available_bytes gauge
kafka_producer_buffer_available_bytes{application="orders-service",client_id="order-producer",kafka_version="4.2.2"} 3.3554432E7
# TYPE kafka_producer_record_error_total counter
kafka_producer_record_error_total{application="orders-service",client_id="order-producer",kafka_version="4.2.2"} 0.0
# TYPE kafka_producer_record_retry_total counter
kafka_producer_record_retry_total{application="orders-service",client_id="order-producer",kafka_version="4.2.2"} 0.0
# TYPE kafka_producer_record_send_total counter
kafka_producer_record_send_total{application="orders-service",client_id="order-producer",kafka_version="4.2.2"} 1000.0
  • The response is the Prometheus text format, version=0.0.4, with 633 lines for one producer and one consumer: about 200 metric families, each with a # HELP and a # TYPE line, plus one line per tag combination.
  • Kafka's cumulative metrics, whose names end in -total, became counters, 37 for the producer and 31 for the consumer. Everything else, including averages, rates and maximums, became a gauge.
  • Names were converted to Prometheus style: record-send-total in the group producer-metrics became kafka_producer_record_send_total, with the value 1000.0. record_error_total and record_retry_total are 0.0, as before.
  • Every sample carries the label application="orders-service", a common tag set once on the registry. Spring Boot sets the same with management.metrics.tags.application; it tells the series of different services apart when several use the same client.id.
  • buffer_available_bytes is printed as 3.3554432E7, the 32 MB buffer in Java's double format, which Prometheus parses as a number.
  • The consumer lag series has the labels partition="0" and topic="orders" and the value 700, the same as the direct read of records-lag. records_lag_max is 900: the lag after the first poll returned 100 records.

The binders were created when the clients were, but bound only after the clients had worked. Kafka creates per-topic and per-partition metrics on first use, and KafkaClientMetrics registers the metrics present at binding and then checks for new ones on a schedule, every 60 seconds by default. Spring Boot binds KafkaClientMetrics to the clients its Kafka factories create and serves the registry at /actuator/prometheus. For one service, 600 series is fine; across hundreds of instances, many teams drop the families they never chart with a Micrometer MeterFilter.

Client ids and JMX names

Client metrics are published under MBean names that contain the client.id. Two clients with the same id in one JVM therefore compete for the same name. This program creates two producers with client.id=checkout and one without an id:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.management.ManagementFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;

public class ClientJmx {

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        String bootstrap = broker.getBrokersAsString();
        try (Admin admin = Admin.create(Map.<String, Object>of("bootstrap.servers", bootstrap))) {
            admin.createTopics(List.of(new NewTopic("orders", 1, (short) 1))).all().get();
        }
        MBeanServer jmx = ManagementFactory.getPlatformMBeanServer();
        try (KafkaProducer<String, String> first = producer(bootstrap, "checkout");
                KafkaProducer<String, String> second = producer(bootstrap, "checkout");
                KafkaProducer<String, String> unnamed = producer(bootstrap, null)) {
            for (int i = 0; i < 10; i++) {
                first.send(new ProducerRecord<>("orders", "from first")).get();
            }
            second.send(new ProducerRecord<>("orders", "from second")).get();
            unnamed.send(new ProducerRecord<>("orders", "from unnamed")).get();

            TreeSet<String> names = new TreeSet<>();
            for (ObjectName n : jmx.queryNames(new ObjectName(
                    "kafka.producer:type=producer-metrics,*"), null)) {
                names.add(n.toString());
            }
            names.forEach(System.out::println);
            ObjectName checkout = new ObjectName(
                    "kafka.producer:type=producer-metrics,client-id=checkout");
            System.out.println("record-send-total for client-id=checkout: "
                    + jmx.getAttribute(checkout, "record-send-total"));
            System.out.println("first producer's own metric:  " + metric(first));
            System.out.println("second producer's own metric: " + metric(second));
        } finally {
            broker.destroy();
        }
    }

    static Object metric(KafkaProducer<String, String> producer) {
        return producer.metrics().entrySet().stream()
                .filter(e -> e.getKey().group().equals("producer-metrics")
                        && e.getKey().name().equals("record-send-total"))
                .findFirst().orElseThrow().getValue().metricValue();
    }

    static KafkaProducer<String, String> producer(String bootstrap, String clientId) {
        Map<String, Object> props = new HashMap<>(Map.of(
                "bootstrap.servers", bootstrap));
        if (clientId != null) {
            props.put("client.id", clientId);
        }
        return new KafkaProducer<>(props, new StringSerializer(), new StringSerializer());
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // 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 {
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1);
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
kafka.producer:type=producer-metrics,client-id=checkout
kafka.producer:type=producer-metrics,client-id=producer-1
record-send-total for client-id=checkout: 1.0
first producer's own metric:  10.0
second producer's own metric: 1.0
  • Only two producer MBeans exist for three producers: one for checkout and one for producer-1, the id Kafka generated for the unnamed producer.
  • The checkout MBean reports 1 record sent, the second producer's count. The first producer had sent 10, as its own metrics() shows, but JMX no longer shows it. A dashboard built from JMX would silently miss that producer.
  • Generated ids such as producer-1 depend on creation order and change after a restart, which breaks dashboards and alerts that use the id.

Give every client a stable, unique client.id, for example the service name plus the purpose, and add an instance number when several run in one JVM. Brokers also use the client id in quotas and in request logs. Since Kafka 3.7, clients can additionally push their metrics to the brokers (KIP-714), so that operators see client health without access to the applications; this needs a metrics plugin on the brokers and was not run here.

Choosing what to alert on

Alerts and what they catch
AlertConditionCatches
Offline partitionsOfflinePartitionsCount > 0Data that cannot be read or written: page someone
Durable writes failingUnderMinIsrPartitionCount > 0acks=all producers timing out
Lost redundancyUnderReplicatedPartitions > 0 for several minutesA broker down or a follower that cannot keep up
No controllerSum of ActiveControllerCount is not 1A KRaft quorum without a leader
Saturated brokerRequestHandlerAvgIdlePercent below 0.3Too few I/O threads or too much load
Failing producersrecord-error-rate > 0Records that were not written
Slow consumersLag growing for several minutesConsumers that cannot keep up or have stopped
Disk filling upFree space on the log directoriesRetention set too long for the traffic

For lag, which needs its own tooling, see consumer lag monitoring. The settings that change these numbers are covered on Kafka performance tuning, and the operations that fix them on Kafka cluster administration. In a Spring Boot application, Actuator publishes the client metrics shown here; see Spring Kafka monitoring.