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.
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=MessagesInPerSecCountorg.apache.kafka.common.metricsrecord-send-totalproducer-metricsclient-idJmxReportermetric.reporters
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:
| Metric | Where | Healthy value | Shows |
|---|---|---|---|
UnderReplicatedPartitions | Each broker | 0 | Followers that fell behind or brokers that are down |
UnderMinIsrPartitionCount | Each broker | 0 | Partitions that reject acks=all |
OfflinePartitionsCount | Active controller | 0 | Partitions with no leader: no reads or writes |
ActiveControllerCount | Controllers | 1 in total | Whether the KRaft quorum has a leader |
RequestHandlerAvgIdlePercentNetworkProcessorAvgIdlePercent | Each broker | Well above 0.3 | Broker threads running out of capacity |
TotalTimeMs | Each broker | Stable percentiles | Slow produce or fetch handling |
record-error-totalrecord-retry-total | Producers | 0, or flat | Failed or retried sends |
records-lag-max | Consumers, groups | Small and not growing | Consumers falling behind |
The programs start brokers inside the JVM, so they can read the broker's MBeans from the same MBeanServerEmbeddedKafkaKraftBrokerspring-kafka-testKafkaClusterTestKit
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:
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);
}
}
}
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
domains:kafka.* for request handling and replication,kafka.server for requests,kafka.network for log segments,kafka.log for the controller, and the coordinators for groups and transactions.kafka.controller - The per-topic
counted exactly 1,000 messages forMessagesInPerSec . Despite the name, the MBean has a running total inorders ; the rates are inCount and similar attributes.OneMinuteRate - The broker-wide
is a little higher than 1,000. The extra messages are the consumer group's offset commits, which are records inMessagesInPerSec .__consumer_offsets andBytesInPerSec 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.BytesOutPerSec includes the 50 partitions ofPartitionCount , created when the group first committed.__consumer_offsets- With one broker, there is nothing to replicate:
andUnderReplicatedPartitions are 0,UnderMinIsrPartitionCount is 1 because this node is also the controller, and no partition is offline.ActiveControllerCount - Request metrics are tagged by request type and API version.
is a histogram with percentiles; it splits further intoTotalTimeMs ,RequestQueueTimeMs ,LocalTimeMs andRemoteTimeMs , which show where a slow request spent its time.ResponseSendTimeMs
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"
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=2acks=allacks=1
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);
}
}
}
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
, because 2 replicas meetacks=all . 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.min.insync.replicas=2 - 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
writes kept working.acks=1 - The
writes failed. The broker answeredacks=all , which is retriable, so the producer retried untilNOT_ENOUGH_REPLICAS , 3 seconds here, ran out, and the send failed withdelivery.timeout.ms . The producer'sTimeoutException shows the retries that happened in that time.record-retry-total
This is the reason to monitor UnderMinIsrPartitionCountUnderReplicatedPartitionsacks=1describeTopicskafka-topics.sh --describe --under-replicated-partitions--under-min-isr-partitions
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:
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);
}
}
}
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)]
is 1000, andrecord-send-total andrecord-error-total are 0: every record was sent at the first attempt. These are the producer metrics to alert on.record-retry-total andbatch-size-avg show how well the producer batched: well over a hundred records per request.records-per-request-avg is the compressed size divided by the original size, so lower is better.compression-rate-avg is the free part of the 32 MBbuffer-available-bytes . When it approaches 0,buffer.memory starts to block.send() is the largest lag the consumer saw in the current time window, andrecords-lag-max 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.records-lag- Micrometer's
turned the consumer's metrics into well over a hundred meters, named likeKafkaClientMetrics , with the Kafka tags pluskafka.consumer.fetch.manager.records.lag . Spring Boot does this automatically for the clients it creates.kafka.version
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
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 KafkaClientMetricsPrometheusMeterRegistrymicrometer-registry-prometheus/metrics
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);
}
}
}
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,
, with 633 lines for one producer and one consumer: about 200 metric families, each with aversion=0.0.4 and a# HELP line, plus one line per tag combination.# TYPE - Kafka's cumulative metrics, whose names end in
, became counters, 37 for the producer and 31 for the consumer. Everything else, including averages, rates and maximums, became a gauge.-total - Names were converted to Prometheus style:
in the grouprecord-send-total becameproducer-metrics , with the value 1000.0.kafka_producer_record_send_total andrecord_error_total are 0.0, as before.record_retry_total - Every sample carries the label
, a common tag set once on the registry. Spring Boot sets the same withapplication="orders-service" ; it tells the series of different services apart when several use the samemanagement.metrics.tags.application .client.id is printed asbuffer_available_bytes , the 32 MB buffer in Java's double format, which Prometheus parses as a number.3.3554432E7- The consumer lag series has the labels
andpartition="0" and the value 700, the same as the direct read oftopic="orders" .records-lag is 900: the lag after the first poll returned 100 records.records_lag_max
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 KafkaClientMetricsKafkaClientMetrics/actuator/prometheusMeterFilter
Client ids and JMX names
Client metrics are published under MBean names that contain the client.idclient.id=checkout
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);
}
}
}
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
and one forcheckout , the id Kafka generated for the unnamed producer.producer-1 - The
MBean reports 1 record sent, the second producer's count. The first producer had sent 10, as its owncheckout shows, but JMX no longer shows it. A dashboard built from JMX would silently miss that producer.metrics() - Generated ids such as
depend on creation order and change after a restart, which breaks dashboards and alerts that use the id.producer-1
Give every client a stable, unique client.id
Choosing what to alert on
| Alert | Condition | Catches |
|---|---|---|
| Offline partitions | OfflinePartitionsCount | Data that cannot be read or written: page someone |
| Durable writes failing | UnderMinIsrPartitionCount | acks=all |
| Lost redundancy | UnderReplicatedPartitions | A broker down or a follower that cannot keep up |
| No controller | Sum of ActiveControllerCount | A KRaft quorum without a leader |
| Saturated broker | RequestHandlerAvgIdlePercent | Too few I/O threads or too much load |
| Failing producers | record-error-rate | Records that were not written |
| Slow consumers | Lag growing for several minutes | Consumers that cannot keep up or have stopped |
| Disk filling up | Free space on the log directories | Retention set too long for the traffic |
For lag, which needs its own tooling, see