๐ŸŽ‰ 75% of content is free forever โ€” Unlock Premium from $10/mo โ†’
CW
NEWSLIVESearch All Content
๐Ÿ’ผ Servicesโ„น๏ธ Aboutโœ‰๏ธ ContactView Pricing Plansfrom $10

Kafka Monitoring: Metrics That Predict Outages

Apache KafkaMonitoringโญ Premium

Kafka Monitoring: Metrics That Predict Outages

Senior level ยท Fewer graphs, better thresholds, and alerts that fire before users notice.

Prerequisites

  • !JMX basics and exporter patterns
  • !Consumer group offsets and lag

What You'll Learn

  • 1Name the small set of signals that predict Kafka incidents
  • 2Scrape broker JMX metrics into Prometheus with useful labels
  • 3Write alert rules with windows long enough to ignore blips
  • 4Diagnose a lag spike from per-partition data instead of an average

Four signals that predict trouble

Kafka emits hundreds of metrics, and almost all incidents announce themselves through four of them. Under-replicated partitions tells you durability is degraded. Offline partitions tells you data is unreachable. Aggregate consumer lag tells you the pipeline is falling behind. Produce and fetch request failure rates tell you clients are being rejected rather than merely slow.

Everything else supports those four: request latency explains why lag is growing, ISR shrink rate explains why replication is degraded, and bytes in and out explain whether the cause is load or a fault. Build dashboards around the four, keep the rest as drill-downs, and you will spend far less time staring at graphs during an incident.

Broker metrics and what each one hides

# The JMX beans worth exporting, grouped by the question they answer
kafka.server:ReplicaManager:
  UnderReplicatedPartitions:   # partitions missing an in-sync follower
  OfflinePartitionsCount:      # partitions with no leader at all
  IsrShrinkPerSec:             # how often followers fall behind
  IsrExpandsPerSec:            # how often they recover
  ActiveControllerCount:       # must be exactly one cluster-wide

kafka.server:BrokerTopicMetrics:
  MessagesInPerSec:            # ingest rate, label by topic
  BytesOutPerSec:              # egress, watch for a runaway consumer
  FailedProduceRequestsPerSec: # rejections, not retries
  FailedFetchRequestsPerSec:   # usually authorization or missing offsets

kafka.network:RequestMetrics:
  TotalTimeMs:                 # histogram per request type
  QueueTimeMs:                 # time before a handler picked it up

ActiveControllerCount is a special case. A value of zero means no controller was elected and the cluster cannot make leadership changes; a value of two means two nodes believe they are in charge during an election. Both are critical, and neither produces any other symptom until clients start timing out on metadata requests.

QueueTimeMs deserves more attention than it gets. When TotalTimeMs rises while QueueTimeMs rises with it, the broker is saturated and you need more capacity. When TotalTimeMs rises but QueueTimeMs stays flat, the work itself got slower, which points at disk latency or a follower fetching across a degraded link.

Getting JMX metrics into Prometheus

# jmx-exporter config: kafka-broker.yml
hostPort: localhost:9999
lowercaseOutputName: true
lowercaseOutputLabelNames: true
rules:
  - pattern: "kafka.server<type=ReplicaManager, name=([A-Za-z]+)><>Value"
    name: kafka_replica_manager_$1
    type: GAUGE

  - pattern: "kafka.server<type=BrokerTopicMetrics, name=([A-Za-z]+), topic=(\w+)><>Count"
    name: kafka_broker_topic_$1_total
    labels:
      topic: $2
    type: COUNTER

  - pattern: "kafka.network<type=RequestMetrics, name=TotalTimeMs, request=(\w+)><>(\w+)"
    name: kafka_request_total_time_ms_$2
    labels:
      request: $1
    type: GAUGE
# prometheus.yml scrape config
scrape_configs:
  - job_name: kafka-brokers
    static_configs:
      - targets: [kafka1:9404, kafka2:9404, kafka3:9404]
    relabel_configs:
      - source_labels: [__address__]
        target_label: instance

  - job_name: kafka-connect
    static_configs:
      - targets: [connect:9404]

Attach the exporter as a Java agent rather than opening the JMX port to the network. An unauthenticated JMX port is effectively remote code execution on that host, and the exporter pattern keeps the metrics interface narrow and scrape-only.

Alerts with windows long enough to ignore blips

groups:
  - name: kafka-critical
    rules:
      - alert: KafkaOfflinePartitions
        expr: kafka_replica_manager_offlinepartitionscount  greater_than 0
        for: 1m
        labels:
          severity: critical
        annotations:
          summary: "partitions with no leader"

      - alert: KafkaUnderReplicated
        expr: kafka_replica_manager_underreplicatedpartitions  greater_than 0
        for: 10m
        labels:
          severity: warning
        annotations:
          summary: "partitions under-replicated for ten minutes"

      - alert: KafkaConsumerLagSustained
        expr: sum by (group, topic) (kafka_consumer_lag)  greater_than 50000
        for: 15m
        labels:
          severity: warning
        annotations:
          summary: "consumer group far behind log end"

      - alert: KafkaProduceErrors
        expr: rate(kafka_broker_topic_failedproducerequestspersec_total[5m])  greater_than 0.5
        for: 5m
        labels:
          severity: critical

The for clause is where most teams get it wrong. A broker restarting during a rolling deploy shows under-replicated partitions for two to four minutes, so a one minute threshold pages on routine maintenance. Ten minutes still catches a genuinely stuck follower while staying quiet through every planned event.

๐Ÿ’กAlert on burn rate, not on absolute lag

Raw lag has no meaning without a drain rate. A hundred thousand records behind is an incident when consumption is five hundred per second and a non-event when it is two million. Alert on projected time to clear rather than on a fixed record count.

Consumer lag: aggregate numbers lie

kafka-consumer-groups.sh --bootstrap-server kafka1:9092 \
  --describe --group order-processor

# GROUP           TOPIC    PART  CURRENT    END        LAG
# order-processor orders   0     918224     918310     86
# order-processor orders   1     918102     918102     0
# order-processor orders   2     901455     918109     16654
# order-processor orders   3     918099     918101     2

The mean lag here is about four thousand, which describes nothing useful. One partition is sixteen thousand behind while three are effectively current, which points at a hot key, a poisoned record, or a single stuck instance rather than a capacity shortfall. Aggregate lag is good for trending; per-partition lag with a count of partitions behind a threshold is what you page on.

Dashboards, alerts and runbooks are different artefacts

ArtefactAudienceTime horizonExample
DashboardWhoever is investigatingNow to weeksPer-partition lag, ISR size, request latency
AlertThe person on callMinutesOffline partitions sustained for one minute
RunbookThe responder at 3amThe incident itselfSteps to identify and retire a stuck follower

Conflating them produces dashboards full of alert thresholds and alerts that require interpretation before anyone can act. A dashboard should answer questions without narration, an alert should carry enough context in its annotations to be actionable, and a runbook should exist for every alert you are willing to wake someone for.

Health checks that do not lie

@Component
public class KafkaHealthIndicator implements HealthIndicator {
    private final AdminClient admin;

    @Override
    public Health health() {
        try {
            ListTopicsOptions opts = new ListTopicsOptions().timeoutMs(2000);
            admin.listTopics(opts).all().get();

            DescribeTopicsResult result = admin.describeTopics(
                Collections.singleton("orders"));
            TopicDescription td = result.all().get(2, TimeUnit.SECONDS).get("orders");

            long offline = 0;
            for (TopicPartitionInfo p : td.partitions()) {
                if (p.leader() == null) {
                    offline = offline + 1;
                }
            }

            if (offline > 0) {
                return Health.down().withDetail("offlinePartitions", offline).build();
            }
            return Health.up()
                .withDetail("partitions", td.partitions().size())
                .build();
        } catch (Exception e) {
            return Health.down().withDetail("error", e.getMessage()).build();
        }
    }
}

A health check that only proves the port is open tells you nothing about whether the service can do its job. Check metadata responsiveness and then the specific topic or group the instance depends on, with short deadlines so a slow broker degrades health rather than hanging the check thread pool.

Correlating broker, producer and consumer signals

Most Kafka incidents are misdiagnosed because the responder looks at one layer in isolation. Rising consumer lag looks like a consumer problem until you check that the broker's request latency also rose at the same moment, which points at a broker-side bottleneck rather than slow application code. Producer throughput dropping looks like a client issue until you notice that the ISR shrank on the same partitions a minute earlier, which means the broker stopped acknowledging writes because the ISR floor was no longer met. The skill is not reading individual metrics; it is ordering them in time and looking for the layer that moved first.

A practical correlation workflow starts from the symptom the user reported, which is almost always end-to-end latency or missing data, then works backwards through four layers. First, check consumer lag and whether it is concentrated on specific partitions. Second, check whether those partitions are on brokers that show elevated request latency or under-replication. Third, check whether producer failure rates rose before the lag did, which would indicate the broker rejected writes. Fourth, check whether a deploy, a rebalance or a network change coincided with the first anomaly. Each step takes a minute on a well-built dashboard and eliminates a layer of guesswork.

The time alignment matters more than the individual graphs. Metrics scraped at one-minute intervals can make a cause that happened forty seconds before an effect look simultaneous, so during an incident drop to ten-second resolution and look at the raw series rather than a five-minute average. If the broker latency spike leads the lag growth by one scrape interval, the broker is the cause and the consumer is a victim; if the lag growth leads the latency spike, the consumer is generating load that the broker is struggling to absorb, and the fix is on the consumer side or in capacity, not in broker tuning.

SymptomFirst checkLikely causeFirst fix
Consumer lag rising on one partitionBroker latency for that partition's leaderHot key or a stuck consumer instanceRebalance or rekey
Lag rising on all partitionsProduce failure rate and ISR sizeBroker under-replication or disk saturationAdd capacity, check disk
Producer latency spiking intermittentlyQueue time versus service time on the brokerGC pause or network blipCheck broker GC, network path
Consumer lag oscillatingRebalance frequency in group metricsPoll loop exceeding intervalShrink batch, move work out
Missing records with no lagTransaction abort rate, DLQ topic sizeAborted transactions or swallowed errorsCheck transaction timeouts

The last row is the one teams discover too late. If consumer lag is healthy but records are missing from the sink, the problem is not throughput; it is either an aborted transaction that was never retried or an error handler that swallowed a poison record into a dead letter queue that nobody monitors. Alerting on dead letter queue depth and transaction abort rate closes that gap, and both are cheap to add once you realize that lag alone does not tell you whether the data arrived correctly, only whether it arrived at all.

Common Mistakes

Alerting on under-replicated partitions with a one minute window

Fix: Use a ten minute window. Rolling restarts legitimately produce short windows of under-replication, and a tight threshold trains the team to ignore the page.

Tracking average consumer lag across a topic

Fix: Alert on maximum per-partition lag and on the count of partitions past a threshold. An average hides the single hot partition that is actually causing the backlog.

Exposing an unauthenticated JMX port to scrape metrics

Fix: Run the JMX exporter as a Java agent on localhost. A reachable JMX port is remote code execution on the broker host.

Building dashboards that no alert links to

Fix: Every alert should point at a dashboard that explains it, and every dashboard panel should have a documented owner and a reason to exist.

Best Practices

  • Page only on offline partitions, sustained under-replication, sustained lag and rising failure rates
  • Export request time split into queue time and service time so saturation and slowness stay distinguishable
  • Label metrics by topic and group at scrape time, because cluster-wide averages answer no useful question
  • Keep exactly one active controller and alert on any other value
  • Write a runbook entry for every alert, or delete the alert

Interview Questions

Q1: Which Kafka metric would you alert on first for a new cluster?

OfflinePartitionsCount, then UnderReplicatedPartitions. Offline means data is unreachable and under-replicated means durability is reduced; both are conditions that need no rate interpretation.

Q2: How do you distinguish a saturated broker from a slow one?

Split request time into queue time and processing time. Rising queue time with rising total time means capacity is exhausted; flat queue time with rising total time points at disk or network latency.

Q3: Why is average consumer lag a poor alert?

Averages hide partition skew. One hot partition can be hours behind while the mean looks fine, so alert on maximum per-partition lag or on the number of partitions past a threshold.

Q4: What does an ActiveControllerCount of zero indicate?

No controller was elected, so leadership changes, topic creation and partition reassignment are all blocked until election succeeds. Clients then fail on metadata requests rather than on fetches.

Q5: How would you monitor Kafka across two datacenters?

Scrape per datacenter and aggregate by region label, then alert on inter-datacenter replication lag and on heartbeat loss between regions, because a healthy cluster in each region can still hide a broken link between them.

Key Takeaways

  • Offline partitions, under-replication, sustained lag and request failures are the four signals that predict incidents
  • Queue time versus service time separates a saturated broker from a slow disk
  • Scrape JMX through an exporter agent on localhost rather than opening the JMX port
  • Alert windows must outlast rolling restarts, or the team learns to ignore the page
  • Per-partition lag beats aggregate lag, and every alert needs a linked dashboard and a runbook
๐Ÿ”’

Premium Content

Kafka Monitoring: Metrics That Predict Outages

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

๐ŸŽฏEnd-to-end Projects
๐Ÿ’ผInterview Prep
๐Ÿ“œCertificates
๐ŸคCommunity Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

โ€”
โ˜†โ˜†โ˜†โ˜†โ˜†
0 ratings

Rate & Feedback

Advertisement