00:00

Kafka Monitoring and Metrics

Last updated:

Kafka monitoring tells you whether the cluster is healthy before users notice a problem: whether every partition has a leader and enough in-sync replicas, whether brokers keep up with requests, and whether consumers keep up with producers. Kafka exposes hundreds of metrics; the skill is knowing the dozen that matter and turning them into useful alerts.

This tutorial explains how Kafka exposes metrics, which broker, controller and client metrics to watch and why, how to collect them with Prometheus and Grafana, how Spring Boot applications publish Kafka metrics through Micrometer, and how to design alerts that are actionable rather than noisy.

1. What to Monitor in a Kafka System

LayerQuestion it answersExamples
Data safetyIs every partition available and fully replicated?Offline, under-replicated and under-min-ISR partitions
Cluster controlIs the KRaft quorum healthy?Active controller count, fenced brokers, metadata errors
Broker capacityCan brokers handle the load?Request handler and network idle ratio, request latency, disk usage
ThroughputHow much data flows in and out?Messages and bytes in/out per topic
ClientsAre producers succeeding and consumers keeping up?Producer errors, consumer lag, rebalances
InfrastructureAre the machines healthy?Disk space and I/O, network, CPU, JVM garbage collection

2. How Kafka Exposes Metrics

Brokers, controllers and Java clients publish metrics as JMX MBeans, named like kafka.server:type=ReplicaManager,name=UnderReplicatedPartitions. Remote JMX access is disabled by default; it can be enabled with the JMX_PORT environment variable for processes started with the Kafka scripts, but in production metrics are normally scraped by an agent rather than read over remote JMX. If you do enable remote JMX, secure it.

Client metrics are published by the client application, not by the broker. Consumer lag as seen by the consumer (records-lag-max) therefore appears in your application’s metrics, while tools such as kafka-consumer-groups.sh calculate lag from the broker side using committed offsets.

3. Key Broker Metrics

Metric (MBean)Healthy valueWhat it tells you
kafka.server:type=ReplicaManager,name=UnderReplicatedPartitions0Partitions whose ISR is smaller than the replica set; a broker is down or a follower cannot keep up
kafka.server:type=ReplicaManager,name=UnderMinIsrPartitionCount0Partitions with fewer in-sync replicas than min.insync.replicas; producers with acks=all are failing for these
kafka.controller:type=KafkaController,name=OfflinePartitionsCount0Partitions without a leader: reads and writes are impossible
kafka.server:type=ReplicaManager,name=IsrShrinksPerSec / IsrExpandsPerSecNear 0 in steady stateFollowers falling out of and back into sync; frequent changes indicate network, disk or GC problems
kafka.server:type=KafkaRequestHandlerPool,name=RequestHandlerAvgIdlePercentAbove 0.3How idle the request handler threads are; low values mean the broker is saturated
kafka.network:type=SocketServer,name=NetworkProcessorAvgIdlePercentAbove 0.3How idle the network threads are
kafka.network:type=RequestMetrics,name=TotalTimeMs,request={Produce|FetchConsumer|FetchFollower}Stable, within your latency targetsEnd-to-end request time, split into queue, local, remote and response-send time
kafka.server:type=BrokerTopicMetrics,name=MessagesInPerSec and BytesInPerSec / BytesOutPerSecFollows your traffic patternThroughput per broker, or per topic with the topic= tag
kafka.network:type=RequestChannel,name=RequestQueueSizeSmallRequests waiting for a handler thread

The difference between the first two matters: an under-replicated partition is degraded but still accepts writes; an under-min-ISR partition rejects writes from producers using acks=all with NotEnoughReplicasException. See in-sync replicas for the mechanics.

4. KRaft Controller Metrics

MetricHealthy valueMeaning
kafka.controller:type=KafkaController,name=ActiveControllerCountExactly 1 across the clusterOnly the active controller reports 1. A sum of 0 means no controller is active; more than 1 must never persist
kafka.controller:type=KafkaController,name=FencedBrokerCount0Brokers that have stopped heartbeating and are fenced from leadership
kafka.controller:type=KafkaController,name=ActiveBrokerCountNumber of brokersBrokers currently registered and active
kafka.controller:type=KafkaController,name=LastAppliedRecordLagMsSmallHow far behind the controller is in applying metadata records
kafka.controller:type=KafkaController,name=MetadataErrorCount0Errors while loading or applying metadata

5. Producer and Consumer Metrics

ClientMetric (attribute)Why it matters
Producerrecord-error-rateSends that failed after all retries; any sustained value means lost or redirected data
Producerrequest-latency-avgTime for produce requests; rises with broker load or replication delays
Producerrecord-queue-time-avg, batch-size-avgHow long records wait to be batched and how full batches are; see performance tuning
Producerbuffer-available-bytesRemaining send buffer; near zero means send() will block
Consumerrecords-lag-max (consumer-fetch-manager-metrics)Largest lag across the consumer’s partitions
Consumercommit-latency-avg, rebalance-rate-per-hourSlow commits and frequent rebalances both hurt throughput

6. Collecting Metrics with Prometheus and Grafana

Kafka metrics pipeline with Prometheus and GrafanaEach broker and controller runs the Prometheus JMX exporter as a Java agent, which exposes JMX metrics over HTTP. Spring Boot applications expose Kafka client metrics through Micrometer at the actuator prometheus endpoint. Prometheus scrapes both, evaluates alert rules and sends alerts to Alertmanager, while Grafana shows dashboards from the stored metrics. Brokers and controllersJMX MBeans+ JMX exporter agent :7071 Spring Boot servicesMicrometer Kafka metrics/actuator/prometheus Prometheusscrape, store,evaluate alert rules Grafanadashboards Alertmanageron-call notifications scrape scrape query alerts
A common open-source monitoring stack: exporters expose metrics, Prometheus scrapes and alerts, Grafana visualises.

The Prometheus JMX exporter runs as a Java agent inside each Kafka process and serves the JMX metrics over HTTP. Download the agent JAR from the Prometheus JMX exporter project, then add it to the broker’s JVM options:

Broker startup environment
export KAFKA_OPTS="-javaagent:/opt/jmx-exporter/jmx_prometheus_javaagent.jar=7071:/opt/jmx-exporter/kafka.yml"
bin/kafka-server-start.sh config/server.properties
kafka.yml (JMX exporter rules, minimal)
lowercaseOutputName: true
rules:
  # kafka.server:type=ReplicaManager,name=UnderReplicatedPartitions -> kafka_server_replicamanager_underreplicatedpartitions
  - pattern: "kafka.(server|controller|network)<type=(.+), name=(.+)><>Value"
    name: "kafka_$1_$2_$3"
  - pattern: "kafka.(server|network)<type=(.+), name=(.+)><>(Count|OneMinuteRate)"
    name: "kafka_$1_$2_$3_$4"

Start with a small set of rules for the metrics in this tutorial and add more as needed; exporting every MBean of a large cluster creates very many time series. Then add each broker’s :7071 endpoint to the Prometheus scrape configuration.

7. Kafka Metrics in Spring Boot

With Spring Boot Actuator and a Micrometer registry on the classpath, Spring Boot registers Micrometer listeners on the auto-configured producer and consumer factories, so the Kafka client metrics appear in the application’s metrics automatically. The listener container also records a spring.kafka.listener timer, tagged with the result (success or failure), for every listener invocation.

pom.xml (excerpt)
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
  <groupId>io.micrometer</groupId>
  <artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
application.yml
management:
  endpoints:
    web:
      exposure:
        include: health,prometheus
spring:
  kafka:
    listener:
      observation-enabled: true    # optional: tracing and observation instead of plain timers
    template:
      observation-enabled: true

After a restart, /actuator/prometheus contains series such as the consumer’s records-lag-max (exported with a kafka_consumer_fetch_manager_ prefix) and spring_kafka_listener_seconds. Enabling observation replaces the plain listener and template timers with Micrometer observations, which also feed distributed tracing.

Business metrics complete the picture: count processed orders, failed payments or records sent to the dead-letter topic with your own MeterRegistry counters. A rising dead-letter count is often the first sign of a bad deployment.

8. Designing Alerts

AlertCondition (example)Severity
Offline partitionsOfflinePartitionsCount > 0 for 1 minuteCritical: data unavailable
Under-min-ISR partitionsUnderMinIsrPartitionCount > 0 for 2 minutesCritical: acks=all writes fail
No active controllerSum of ActiveControllerCount across controllers is not 1 for 1 minuteCritical
Under-replicated partitionsUnderReplicatedPartitions > 0 for 10 minutesWarning, critical if it persists
Broker saturationRequestHandlerAvgIdlePercent < 0.2 for 10 minutesWarning: add capacity or find the cause
Disk usageLog directory volume above 80 %Warning: a full disk takes the broker offline
Consumer falling behindLag growing for 15 minutes, or estimated time to catch up above your SLAWarning, routed to the owning team
Producer errorsrecord-error-rate > 0 for 5 minutesWarning, routed to the owning team

Use a for duration so short blips during rolling restarts do not page anyone, and route client-side alerts to the team that owns the application, not to the platform team.

9. Common Mistakes

  • Alerting on raw lag numbers. A lag of 50,000 is nothing for a topic receiving 100,000 records per second and serious for one receiving 10. Alert on growth or on time to catch up.
  • Watching only brokers. Many incidents start in clients: a producer silently failing sends, or a consumer stuck in rebalances.
  • Exporting every MBean. Per-partition metrics of a large cluster create huge numbers of time series and slow down Prometheus.
  • Ignoring disk space. Retention settings that do not fit the disks eventually fill them, and a broker with a full disk goes offline.
  • Leaving remote JMX open without authentication; JMX can also change settings, not only read them.

10. Best Practices

  • Start with the five critical alerts: offline partitions, under-min-ISR, active controller, under-replicated partitions and disk space.
  • Build one dashboard per audience: cluster health for the platform team, lag and errors per service for application teams.
  • Correlate with infrastructure metrics (disk I/O, network, GC pauses), which usually explain ISR shrinks and latency spikes.
  • Test your alerts by stopping a broker in a test cluster and checking that the right alerts fire and clear.
  • Record business metrics next to Kafka metrics so you can see impact, not only symptoms.

11. Summary

Kafka publishes broker, controller and client metrics through JMX. The most important ones answer three questions: is data safe (offline, under-min-ISR and under-replicated partitions), is the cluster in control (one active controller, no fenced brokers), and are brokers and clients keeping up (handler idle ratio, request time, producer errors, consumer lag). Collect broker metrics with the Prometheus JMX exporter, application metrics with Micrometer in Spring Boot, and alert on a small set of conditions with sensible durations and clear owners.

13. References