Kafka Monitoring
Overview
Monitoring Apache Kafka is essential for maintaining reliable, scalable, and performant event streaming platforms. A comprehensive monitoring strategy covers broker health, consumer lag, throughput metrics, and resource utilization across the entire Kafka ecosystem.
Why Monitoring Matters
- Early Detection: Identify issues before they impact production workloads
- Capacity Planning: Understand growth patterns for infrastructure scaling
- Performance Optimization: Tune configurations based on real metrics
- SLA Compliance: Ensure message delivery guarantees are met
Defining "healthy" comes before charting anything. A three-broker cluster pushing 40,000 messages per second is healthy when every partition's in-sync replica set matches its assigned replicas, when the controller has held office for days rather than minutes, and when each consumer group drains its backlog inside the agreed processing window. Those three statements map onto UnderReplicatedPartitions, ActiveControllerCount and consumer lag, which is why a dashboard missing any one of them always surprises somebody at three in the morning. A metric earns its place only if it moves before users notice, so every alert you write should name the metric, the number that triggers it, and the reason that number matters to a person rather than to the cluster.
Monitoring also protects capacity decisions. Kafka rarely degrades politely: it absorbs load into the page cache until the cache saturates, then throughput falls off a cliff as reads turn into disk seeks. Watching bytes in per second against free page cache tells you the cliff is coming weeks before it arrives, and a broker that has run at 70% of its network capacity for a month is a very different planning conversation from one that spiked to 95% for ten minutes.
Key Kafka Metrics
Broker Metrics
| Metric | Description | Warning Threshold |
|---|---|---|
kafka.server.BrokerTopicMetrics.MessagesInPerSec | Messages received per second | Varies by workload |
kafka.server.BrokerTopicMetrics.BytesInPerSec | Bytes received per second | > 80% network capacity |
kafka.server.BrokerTopicMetrics.BytesOutPerSec | Bytes sent per second | > 80% network capacity |
kafka.network.RequestMetrics.TotalRequestsPerSec | Total requests per second | > 10,000 req/s |
kafka.server.ReplicaManager.UnderReplicatedPartitions | Partitions with missing replicas | > 0 |
Consumer Group Metrics
kafka_consumer_group_lag{topic="orders", partition="0", group="order-processor"} 15234
kafka_consumer_group_lag{topic="orders", partition="1", group="order-processor"} 8921
kafka_consumer_group_lag{topic="orders", partition="2", group="order-processor"} 23456
Lag is a partition number, never a group number: it is the distance between the high watermark the broker will serve and the offset the group last committed. Partition 2 sitting at 23,456 records is alarming behind a producer trickling five records per second, because nothing has moved for over an hour, and completely harmless behind a producer pushing two million records per second, because that backlog clears in twelve milliseconds. The alert that survives contact with production therefore divides lag by the recent produce rate instead of comparing against a fixed count, and it evaluates per partition so a single hot partition cannot hide inside a group average.
Lag also behaves oddly during rebalances. While partitions are being revoked and re-assigned the group stops committing, lag climbs, then drops back once the new owners catch up â a sawtooth pattern that means nothing about consumer capacity. A rebalance storm caused by max.poll.interval.ms being too low looks like repeated versions of that sawtooth, and the fix is in the consumer configuration rather than in the cluster.
Producer Metrics
record-error-rate: Failed record sendsrecord-send-rate: Successful record sendsbatch-size-avg: Average batch size in bytescompression-rate-avg: Compression ratio
Producer metrics are the earliest warning system the platform has. A rising record-error-rate with a stable record-send-rate usually means brokers are rejecting writes because in-sync replicas fell below min.insync.replicas, and the client is retrying rather than failing loudly. batch-size-avg drifting far below the configured batch.size says your topics are partitioned too finely for the traffic you actually send, so each partition carries a dribble of records and the client can never fill a batch. And buffer-available-percent pinning below 100% means the sender thread is blocked waiting for the record accumulator to drain, which is backpressure surfacing long before an exception does.
JMX Metrics Deep Dive
Enabling JMX on Kafka Brokers
# Set JMX options in server.properties or environment
export KAFKA_JMX_OPTS="-Dcom.sun.management.jmxremote \
-Dcom.sun.management.jmxremote.port=9999 \
-Dcom.sun.management.jmxremote.authenticate=false \
-Dcom.sun.management.jmxremote.ssl=false"
Key JMX MBeans
# Python example using jmxquery
from jmxquery import JMXQuery
jmx_url = "service:jmx:rmi:///jndi/rmi://localhost:9999/jmxrmi"
queries = [
JMXQuery(
metric_name="kafka_server_brokertopicmetrics_messagesinpersec_count",
metric_type="gauge",
metric_tags={"topic": "Orders"}
),
JMXQuery(
metric_name="kafka_server_replicamanager_underreplicatedpartitions",
metric_type="gauge"
)
]
results = JMXQuery(jmx_url).query(queries)
print(results)
Critical JMX MBeans
# jmx_exporter_config.yml
rules:
- pattern: kafka.server<type=BrokerTopicMetrics, name=MessagesInPerSec><>Count
name: kafka_server_brokertopicmetrics_messagesinpersec_count
type: counter
- pattern: kafka.server<type=ReplicaManager, name=UnderReplicatedPartitions><>Value
name: kafka_server_replicamanager_underreplicatedpartitions
type: gauge
- pattern: kafka.network<type=RequestMetrics, name=TotalRequestsPerSec, request=(.+), error=(.+)><>Count
name: kafka_network_requestmetrics_totalrequestspersec_count
labels:
request: $1
error: $2
Getting metrics out of the process
JMX is the only interface Kafka gives you for internal state, but raw JMX is awkward to consume: it needs a port, it speaks the RMI protocol, and the JVM flags above enable it with authentication switched off. Binding port 9999 to 0.0.0.0 on a production broker exposes an unauthenticated management endpoint to the network, so either keep com.sun.management.jmxremote.authenticate=true with a password file or bind the port to the loopback interface and let a sidecar scrape it locally. Most teams choose the third option: attach the jmx_exporter Java agent to the broker JVM and have it serve Prometheus text format on 9404 without any extra port opening.
Three approaches dominate, and the choice is about what you need to measure rather than about preference:
| Approach | What it measures well | Typical cost |
|---|---|---|
| jmx_exporter agent | Per-broker and per-topic counters, request latencies | One agent JAR, ~2% CPU |
| Burrow or Cruise Control | Consumer group lag and cluster balance with semantics built in | A second JVM to operate |
| Client-side metrics | End-to-end produce and fetch latency from the application's view | Instrument every application |
The broker agent sees what the broker did; it cannot see that a client spent 400 milliseconds waiting on a metadata refresh. Client-side metrics close that gap, and Burrow replaces hand-written lag arithmetic with committed status, lag, partition assignment and an explicit "healthy" verdict per group.
Prometheus setup
Prometheus Configuration
# prometheus.yml
global:
scrape_interval: 15s
evaluation_interval: 15s
scrape_configs:
- job_name: 'kafka-brokers'
static_configs:
- targets:
- 'kafka-broker-1:9404'
- 'kafka-broker-2:9404'
- 'kafka-broker-3:9404'
metrics_path: /metrics
- job_name: 'kafka-connect'
static_configs:
- targets:
- 'kafka-connect-1:9404'
- 'kafka-connect-2:9404'
- job_name: 'kafka-consumer-groups'
static_configs:
- targets:
- 'kafka-consumer-metrics:9404'
Prometheus Alert Rules
# kafka_alerts.yml
groups:
- name: kafka_alerts
rules:
- alert: KafkaUnderReplicatedPartitions
expr: kafka_server_replicamanager_underreplicatedpartitions > 0
for: 5m
labels:
severity: critical
annotations:
summary: "Under-replicated partitions detected"
description: "{{ $value }} partitions are under-replicated"
- alert: KafkaConsumerLagHigh
expr: kafka_consumer_group_lag > 10000
for: 10m
labels:
severity: warning
annotations:
summary: "Consumer lag is high"
description: "Consumer group {{ $labels.group }} has lag of {{ $value }}"
- alert: KafkaBrokerDown
expr: up{job="kafka-brokers"} == 0
for: 1m
labels:
severity: critical
annotations:
summary: "Kafka broker is down"
description: "Broker {{ $labels.instance }} is unreachable"
Grafana Dashboard Setup
Essential Dashboard Panels
{
"panels": [
{
"title": "Messages In Rate",
"type": "timeseries",
"targets": [
{
"expr": "sum(rate(kafka_server_brokertopicmetrics_messagesinpersec_count[5m]))",
"legendFormat": "{{instance}}"
}
]
},
{
"title": "Consumer Group Lag",
"type": "timeseries",
"targets": [
{
"expr": "sum by (group) (kafka_consumer_group_lag)",
"legendFormat": "{{group}}"
}
]
},
{
"title": "Under Replicated Partitions",
"type": "stat",
"targets": [
{
"expr": "sum(kafka_server_replicamanager_underreplicatedpartitions)"
}
],
"thresholds": {
"steps": [
{"value": 0, "color": "green"},
{"value": 1, "color": "red"}
]
}
}
]
}
Dashboard Best Practices
- Broker Overview: CPU, memory, disk usage, network I/O
- Topic Metrics: Messages/sec, bytes/sec, partition distribution
- Consumer Metrics: Lag, throughput, rebalance frequency
- Cluster Health: ISR size, controller status, log segments
Alerting Strategies
Alert Severity Levels
| Level | Response Time | Examples |
|---|---|---|
| Critical | Immediate | Broker down, under-replicated partitions |
| Warning | 1 hour | High consumer lag, disk space low |
| Info | Next business day | Config changes, rebalances |
Common Alert Patterns
# Consumer lag alert with dynamic threshold
- alert: KafkaConsumerLagExceedsThreshold
expr: |
(
kafka_consumer_group_lag
/ ignoring(group) group_left()
kafka_server_brokertopicmetrics_messagesinpersec_count
) > 300
for: 5m
labels:
severity: warning
annotations:
summary: "Consumer {{ $labels.group }} is falling behind"
Monitoring Best Practices
1. Establish Baselines
- Monitor metrics during normal operations for 1-2 weeks
- Set thresholds based on standard deviations from baseline
- Account for daily/weekly patterns in traffic
2. Implement Health Checks
def kafka_health_check(brokers):
"""Check Kafka cluster health"""
checks = {
'brokers_reachable': check_broker_connectivity(brokers),
'all_partitions_isr': check_isr_status(),
'consumer_lags_healthy': check_consumer_lags(),
'disk_space_adequate': check_disk_usage(),
'jmx_accessible': check_jmx_endpoint()
}
return all(checks.values())
3. Log Aggregation
- Collect Kafka logs with Filebeat or Fluentd
- Index logs in Elasticsearch or Loki
- Create log-based alerts for ERROR messages
4. Distributed Tracing
- Use OpenTelemetry for end-to-end tracing
- Track message flow from producer to consumer
- Monitor end-to-end latency across services
Common Mistakes
Paging on a fixed consumer lag count such as anything above 10,000 records
Fix: Divide lag by the recent produce rate per partition, or use Burrow's committed status, so a healthy catch-up burst never wakes anyone
Exposing port 9999 with authentication disabled so Prometheus can scrape it
Fix: Attach the jmx_exporter agent and scrape loopback on 9404, or enable username and password authentication plus TLS on the JMX port
Labeling every series by partition on topics with hundreds of partitions
Fix: Aggregate to broker or topic level in the export rules and keep partition-level labels for the two or three topics that actually get investigated
Summary
Effective Kafka monitoring requires a multi-layered approach combining JMX metrics, Prometheus collection, Grafana visualization, and intelligent alerting. Focus on consumer lag, broker health, and throughput metrics to ensure your Kafka deployment remains reliable and performant.
See Also
- Kafka Architecture â Core concepts of brokers, topics, partitions, and replication
- Kafka Producer & Consumer â Building producers and consumers with configuration patterns
- Kafka Performance Tuning â Optimizing throughput, latency, and resource utilization