Kafka Monitoring and Metrics
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
| Layer | Question it answers | Examples |
|---|---|---|
| Data safety | Is every partition available and fully replicated? | Offline, under-replicated and under-min-ISR partitions |
| Cluster control | Is the KRaft quorum healthy? | Active controller count, fenced brokers, metadata errors |
| Broker capacity | Can brokers handle the load? | Request handler and network idle ratio, request latency, disk usage |
| Throughput | How much data flows in and out? | Messages and bytes in/out per topic |
| Clients | Are producers succeeding and consumers keeping up? | Producer errors, consumer lag, rebalances |
| Infrastructure | Are 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 value | What it tells you |
|---|---|---|
kafka.server:type=ReplicaManager,name=UnderReplicatedPartitions | 0 | Partitions whose ISR is smaller than the replica set; a broker is down or a follower cannot keep up |
kafka.server:type=ReplicaManager,name=UnderMinIsrPartitionCount | 0 | Partitions with fewer in-sync replicas than min.insync.replicas; producers with acks=all are failing for these |
kafka.controller:type=KafkaController,name=OfflinePartitionsCount | 0 | Partitions without a leader: reads and writes are impossible |
kafka.server:type=ReplicaManager,name=IsrShrinksPerSec / IsrExpandsPerSec | Near 0 in steady state | Followers falling out of and back into sync; frequent changes indicate network, disk or GC problems |
kafka.server:type=KafkaRequestHandlerPool,name=RequestHandlerAvgIdlePercent | Above 0.3 | How idle the request handler threads are; low values mean the broker is saturated |
kafka.network:type=SocketServer,name=NetworkProcessorAvgIdlePercent | Above 0.3 | How idle the network threads are |
kafka.network:type=RequestMetrics,name=TotalTimeMs,request={Produce|FetchConsumer|FetchFollower} | Stable, within your latency targets | End-to-end request time, split into queue, local, remote and response-send time |
kafka.server:type=BrokerTopicMetrics,name=MessagesInPerSec and BytesInPerSec / BytesOutPerSec | Follows your traffic pattern | Throughput per broker, or per topic with the topic= tag |
kafka.network:type=RequestChannel,name=RequestQueueSize | Small | Requests 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
| Metric | Healthy value | Meaning |
|---|---|---|
kafka.controller:type=KafkaController,name=ActiveControllerCount | Exactly 1 across the cluster | Only 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=FencedBrokerCount | 0 | Brokers that have stopped heartbeating and are fenced from leadership |
kafka.controller:type=KafkaController,name=ActiveBrokerCount | Number of brokers | Brokers currently registered and active |
kafka.controller:type=KafkaController,name=LastAppliedRecordLagMs | Small | How far behind the controller is in applying metadata records |
kafka.controller:type=KafkaController,name=MetadataErrorCount | 0 | Errors while loading or applying metadata |
5. Producer and Consumer Metrics
| Client | Metric (attribute) | Why it matters |
|---|---|---|
| Producer | record-error-rate | Sends that failed after all retries; any sustained value means lost or redirected data |
| Producer | request-latency-avg | Time for produce requests; rises with broker load or replication delays |
| Producer | record-queue-time-avg, batch-size-avg | How long records wait to be batched and how full batches are; see performance tuning |
| Producer | buffer-available-bytes | Remaining send buffer; near zero means send() will block |
| Consumer | records-lag-max (consumer-fetch-manager-metrics) | Largest lag across the consumer’s partitions |
| Consumer | commit-latency-avg, rebalance-rate-per-hour | Slow commits and frequent rebalances both hurt throughput |
6. Collecting Metrics with Prometheus and Grafana
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:
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
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.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
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
| Alert | Condition (example) | Severity |
|---|---|---|
| Offline partitions | OfflinePartitionsCount > 0 for 1 minute | Critical: data unavailable |
| Under-min-ISR partitions | UnderMinIsrPartitionCount > 0 for 2 minutes | Critical: acks=all writes fail |
| No active controller | Sum of ActiveControllerCount across controllers is not 1 for 1 minute | Critical |
| Under-replicated partitions | UnderReplicatedPartitions > 0 for 10 minutes | Warning, critical if it persists |
| Broker saturation | RequestHandlerAvgIdlePercent < 0.2 for 10 minutes | Warning: add capacity or find the cause |
| Disk usage | Log directory volume above 80 % | Warning: a full disk takes the broker offline |
| Consumer falling behind | Lag growing for 15 minutes, or estimated time to catch up above your SLA | Warning, routed to the owning team |
| Producer errors | record-error-rate > 0 for 5 minutes | Warning, 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.
12. Related Reading
- Consumer lag: measuring and fixing lag
- Broker failure and recovery: what the metrics show during failures
- Kafka CLI commands: checking groups and topics from the command line
- Spring Boot Actuator: health checks and metrics endpoints
13. References
Kafka Monitoring Interview Questions and Answers
Common interview questions on Kafka Monitoring, from basic to scenario-based, with short answers you can explain in your own words.
Basic questions
Q. How does Kafka expose its metrics, and how do you get them into Prometheus?
Answer: Brokers, controllers and Java clients publish metrics as JMX MBeans. Remote JMX is disabled by default, so the usual approach is the Prometheus JMX exporter running as a Java agent inside each Kafka process, which serves selected MBeans over HTTP for Prometheus to scrape. Spring Boot applications expose their Kafka client metrics through Micrometer at /actuator/prometheus.
Q. What is the difference between UnderReplicatedPartitions and UnderMinIsrPartitionCount?
Answer: UnderReplicatedPartitions counts partitions whose in-sync replica set is smaller than the full replica set: redundancy is reduced, but writes still work. UnderMinIsrPartitionCount counts partitions whose ISR is below min.insync.replicas: producers using acks=all now fail with NotEnoughReplicasException. The first is a warning, the second an outage for durable writes.
Intermediate questions
Q. Which problems can only client-side metrics reveal, and which client metrics would you watch?
Answer: Brokers can look perfectly healthy while an application fails: a producer whose sends expire after all retries, a producer blocked because its buffer is full, or a consumer stuck in repeated rebalances. Watch record-error-rate and buffer-available-bytes on producers, and records-lag-max, rebalance-rate-per-hour and commit-latency-avg on consumers, and route these alerts to the team that owns the application.
Q. What does a low RequestHandlerAvgIdlePercent indicate, and what would you investigate?
Answer: The broker’s request handler threads are busy almost all the time, so requests queue up and latency rises. Look at TotalTimeMs split into queue, local and remote time, at RequestQueueSize, and at disk I/O and GC. Common causes are a hot partition, many small produce requests, slow disks, or followers that make produce requests wait for replication.
Q. Which Kafka metrics does a Spring Boot application expose without extra code?
Answer: With Actuator and a Micrometer registry present, Spring Boot registers Micrometer listeners on the auto-configured producer and consumer factories, so client metrics such as consumer lag and producer error rates are exported. The listener container also records a spring.kafka.listener timer per listener, tagged with success or failure. Enabling observation for the listener and template switches these to Micrometer observations with tracing support.
Tricky and scenario questions
Q. You are asked to set up Kafka alerting from scratch. Which alerts would you create first, and why?
Answer: First the conditions that mean data is unavailable or unsafe: offline partitions above 0, under-min-ISR partitions above 0, the active controller count not equal to 1, and disk usage of log directories above about 80 %. Next, under-replicated partitions that persist for several minutes and sustained broker saturation. Then per-team alerts on consumer lag growth and producer errors. Each alert gets a duration so rolling restarts do not page anyone.
Q. Under-replicated partitions appear on one broker every evening and disappear an hour later. How would you approach it?
Answer: A recurring, time-bound pattern points to load: a batch job or replay at that time. Check which partitions are affected and where their leaders and followers are, then correlate IsrShrinksPerSec with disk I/O, network throughput, request queue time and GC pauses on that broker. Typical fixes are moving hot partitions, throttling the batch job with quotas, or adding capacity on the slow disk or network.