Kafka monitoring in production: consumer lag, broker and client metrics, rebalancing and end-to-end tracing
How to measure consumer lag in offsets and in time, which broker, producer and consumer metrics matter, how to keep rebalances calm, how to trace messages across Kafka with OpenTelemetry, and a runbook for growing lag.
Summary
- Kafka monitoring has three layers: the cluster (under-replicated and offline partitions, ISR changes, request latency, controller health), the clients (producer errors, retries and latency, consumer poll behaviour and rebalances) and the data flow itself (consumer lag per group and partition).
- Consumer lag in offsets tells you how many records are waiting; lag in time tells you how stale the data is. Alert on time lag or on a lag trend relative to your freshness target, not on a fixed offset number.
- End-to-end visibility needs trace context in message headers: OpenTelemetry instrumentation propagates it automatically for most clients, batch consumers use span links, and the messaging semantic conventions keep attributes consistent.
Kafka monitoring is the practice of watching an Apache Kafka deployment from three angles at once: the health of the brokers and their replicated partitions, the behaviour of the producer and consumer clients, and the flow of data between them, most visibly as consumer lag. A cluster can look perfectly healthy while one consumer group falls hours behind, and a consumer can look idle while the real problem is a broker that has quietly dropped out of the in-sync replica set. You only see the full picture when all three layers are measured and connected.
This guide explains how to monitor Kafka in production: how to measure consumer lag correctly, which Kafka metrics matter on brokers, producers and consumers, what rebalancing does to your pipeline, what changes with KRaft, and how to trace a single message from producer to consumer with OpenTelemetry. It closes with example alert rules, a runbook for the most common page ("lag is growing") and a checklist. Thresholds in this article are examples to start from, not recommendations for every cluster.
The three layers of Kafka monitoring
Most Kafka incidents become visible in one layer but are caused in another. Keeping the layers apart helps you ask the right question first.
- Cluster layer. Brokers, partitions, replication and the controller. Questions: are all partitions online and fully replicated, is the controller stable, are requests being served in time, is any broker saturated on disk, network or request handler threads?
- Client layer. Producers and consumers inside your services. Questions: do sends fail or retry, how long do produce requests take, are consumers polling regularly, how often does the group rebalance?
- Data flow layer. The relationship between what was written and what was processed. Questions: how far behind is each consumer group, is the gap growing, and how old is the oldest unprocessed record?
Kafka exposes broker and client metrics through JMX. Common ways to collect them are a JMX to Prometheus exporter running next to each broker, the OpenTelemetry Collector with a JMX-based receiver, and client-side instrumentation in your applications. Consumer lag is special: it is best measured from outside the consumer, by comparing committed offsets with log end offsets, because a crashed or stuck consumer cannot report its own lag.
Consumer lag: offset lag versus time lag
For every partition, the broker knows the log end offset, the offset the next written record will get. Each consumer group commits the offset it will read next. The difference is the offset lag: the number of records written but not yet consumed by that group. The command line tool shows it directly:
kafka-consumer-groups.sh --bootstrap-server kafka-1:9092 \
--describe --group order-service
# columns include CURRENT-OFFSET, LOG-END-OFFSET and LAG per partition
Offset lag is easy to collect but hard to interpret. A lag of 50,000 records is nothing for a topic that receives 100,000 records per second and serious for one that receives ten per minute. That is why you also want time lag: how old the oldest unconsumed record is, or how long the group would need to catch up at its current rate. Time lag maps directly to what the business cares about, for example "order confirmations are at most two minutes late".
| Measure | How to get it | Good for | Watch out for |
|---|---|---|---|
| Offset lag per partition | Log end offset minus committed offset, from the admin API, an exporter or the Collector | Finding hot or stuck partitions | Not comparable across topics with different throughput |
| Offset lag per group (sum) | Sum over all partitions of a group and topic | Dashboards and trend alerts | Hides a single stuck partition behind healthy ones |
| Time lag (estimated) | Offset lag divided by the recent consume rate, or interpolation over recent offsets and timestamps | Freshness SLOs and alerting | Unstable when traffic is near zero |
| Time lag (record age) | Now minus the timestamp of the record being processed, measured in the consumer | Precise end-to-end delay | Only available while the consumer runs; producer clocks must be sane |
records-lag-max | Consumer client metric in consumer-fetch-manager-metrics | Quick view from inside the application | Disappears when the consumer crashes |
Two practical rules follow. First, always keep lag per partition available, even if you alert on the group sum, because partition skew is one of the most common causes of lag. Second, alert on lag that is growing or on time lag that exceeds a freshness target, not on any lag above zero. Some lag is normal: consumers fetch in batches and commit periodically.
Partitions, skew and hot keys
Parallelism in a consumer group is capped by the number of partitions: each partition is assigned to exactly one consumer in the group, so a group with more consumers than partitions leaves some consumers idle. Lag therefore often concentrates on a few partitions. Typical causes:
- Hot keys. The default partitioner hashes the record key. If one customer, tenant or device produces most of the traffic, its partition receives most of the records and its consumer falls behind.
- Uneven processing cost. Some records are much more expensive to process than others, for example because they trigger a slow external call.
- Poison messages. A record that always fails processing blocks its partition if the consumer retries forever. A dead letter queue with a retry budget prevents one record from stalling everything behind it.
- Uneven leadership. If one broker leads many busy partitions, it becomes the bottleneck for producers and consumers alike.
To detect skew, compare lag and the produce rate per partition within a topic. A dashboard that shows the top partitions by lag next to the consumer instance that owns them usually answers "is this a capacity problem or a single partition problem" within seconds.
Broker and cluster metrics that matter
Kafka brokers expose hundreds of metrics. The ones below are the core set described in the Apache Kafka monitoring documentation and the first ones to put on a dashboard. Example alert conditions are illustrations; adapt them to your replication settings and traffic.
| Metric (JMX name) | What it tells you | Example alert condition |
|---|---|---|
kafka.server:type=ReplicaManager,name=UnderReplicatedPartitions | Partitions whose in-sync replica set is smaller than the full replica set | Example: above 0 for more than 5 minutes |
kafka.server:type=ReplicaManager,name=UnderMinIsrPartitionCount | Partitions with fewer in-sync replicas than min.insync.replicas; producers with acks=all get errors | Example: above 0, page immediately |
kafka.controller:type=KafkaController,name=OfflinePartitionsCount | Partitions without an active leader, unavailable for reads and writes | Example: above 0, page immediately |
kafka.controller:type=KafkaController,name=ActiveControllerCount | Whether this node is the active controller; the sum across the cluster should be exactly 1 | Example: cluster sum not equal to 1 for more than 1 minute |
kafka.server:type=ReplicaManager,name=IsrShrinksPerSec and IsrExpandsPerSec | Replicas leaving and rejoining the in-sync set | Example: repeated shrinks without matching expands within 15 minutes |
kafka.controller:type=ControllerStats,name=UncleanLeaderElectionsPerSec | Leaders elected from out-of-sync replicas, which can lose data | Example: any non-zero value |
kafka.network:type=RequestMetrics,name=TotalTimeMs,request=Produce (also FetchConsumer, FetchFollower) | Request latency, broken down further by queue, local, remote and response time | Example: p99 well above your baseline for 10 minutes |
kafka.server:type=KafkaRequestHandlerPool,name=RequestHandlerAvgIdlePercent | How busy the request handler threads are | Example: below 0.3 for 10 minutes |
kafka.network:type=SocketServer,name=NetworkProcessorAvgIdlePercent | How busy the network threads are | Example: below 0.3 for 10 minutes |
kafka.server:type=BrokerTopicMetrics,name=BytesInPerSec, BytesOutPerSec, MessagesInPerSec | Throughput per broker and topic | Usually a dashboard signal, not an alert |
Add the basics from the host or container: disk usage on the log directories, disk I/O wait, network throughput and JVM garbage collection pauses. A full disk takes a broker offline, and long GC pauses are a classic reason for replicas falling out of the ISR.
ISR shrink, explained. A follower replica stays in the in-sync replica set as long as it keeps up with the leader within replica.lag.time.max.ms. If it falls behind, the leader removes it and IsrShrinksPerSec rises; when it catches up, it rejoins and IsrExpandsPerSec rises. Occasional shrink and expand pairs during restarts are normal. Shrinks that keep coming, or that line up with one broker, point to a slow disk, a saturated network link, long GC pauses or an overloaded broker. If the ISR drops below min.insync.replicas, producers using acks=all start receiving errors, which is when a replication problem becomes an application incident.
Producer metrics: latency, errors, retries and batching
Producer problems usually surface as slow or failing requests in the services that write to Kafka. The Java client exposes these metrics in the kafka.producer:type=producer-metrics,client-id=... group; other clients offer similar statistics.
record-error-rate: records per second that failed after all retries. Anything above zero means data that did not reach Kafka, unless your code handles it.record-retry-rate: retried records per second. Rising retries often precede errors and point to leader changes, throttling or broker overload.request-latency-avgandrequest-latency-max: time from sending a produce request to receiving the response.record-queue-time-avg: how long records wait in the producer buffer before being sent. Growing queue time with constant request latency suggests the producer cannot send fast enough.batch-size-avgandrecords-per-request-avg: how well batching works. Very small batches mean many requests and more broker load;linger.msandbatch.sizecontrol the trade-off between latency and throughput.buffer-available-bytesandbufferpool-wait-ratio: if the buffer fills up,send()blocks for up tomax.block.ms, which shows up as latency in the calling service.
Correlate these with application traces. A slow HTTP endpoint that publishes an event is often slow because the producer blocks on a full buffer, which you only see if the produce span sits inside the request trace.
Consumer metrics and rebalancing
A rebalance redistributes partitions among the members of a consumer group. It happens when a consumer joins or leaves, when a consumer is considered dead, or when partitions are added. With the classic eager protocol, every member gives up all its partitions during a rebalance, so the whole group stops consuming until assignment completes. Frequent rebalances are therefore a common cause of lag that seems to come from nowhere.
Useful consumer client metrics, from the consumer-coordinator-metrics and consumer-metrics groups of the Java client:
rebalance-rate-per-hour,rebalance-latency-avgandfailed-rebalance-total: how often and how long the group rebalances.last-rebalance-seconds-ago: useful to see whether a group is stuck in a rebalance loop.time-between-poll-maxandlast-poll-seconds-ago: if the time between polls exceedsmax.poll.interval.ms(default 300,000 ms), the consumer leaves the group and triggers a rebalance.commit-latency-avgandcommit-rate: slow or failing offset commits.records-consumed-rateandfetch-latency-avg: consumption throughput and fetch behaviour.
Three mechanisms reduce the impact of rebalances:
- Cooperative rebalancing (KIP-429). With the
CooperativeStickyAssignor, consumers only give up the partitions that actually move, and keep consuming the rest. This turns a stop-the-world event into a series of small, incremental changes. - Static membership (KIP-345). Setting
group.instance.idper consumer instance lets a consumer restart withinsession.timeout.mswithout triggering a rebalance. This is especially useful for rolling deployments and pods that restart quickly. - The new consumer group protocol (KIP-848). Newer Kafka versions move assignment logic to the broker and make rebalances incremental by design. Check whether your broker and client versions support it before relying on it.
The most common rebalance trigger in practice is slow processing: a consumer fetches up to max.poll.records records, the processing takes longer than max.poll.interval.ms, and the consumer is removed from the group. Either process fewer records per poll, make processing faster, or move slow work off the polling thread.
KRaft versus ZooKeeper: what changes for monitoring
KIP-500 replaced ZooKeeper with KRaft, a Raft-based metadata quorum built into Kafka itself. Kafka 4.0 removed ZooKeeper mode entirely, so new clusters run KRaft, and existing ZooKeeper-based clusters need to migrate before upgrading to 4.x. For monitoring, this means:
- With ZooKeeper, you monitor the ZooKeeper ensemble separately (latency, outstanding requests, session expirations) and watch broker-side metrics such as
kafka.server:type=SessionExpireListener,name=ZooKeeperDisconnectsPerSecandZooKeeperExpiresPerSec. - With KRaft, the controller quorum is part of Kafka. Watch that exactly one active controller exists, that the quorum has a stable leader, and the Raft metrics the controllers expose (the
raft-metricsgroup, for example current state, leader and commit latency). Exact metric names differ between versions, so check the documentation for the version you run. - Either way, keep
OfflinePartitionsCount,ActiveControllerCountand leader election rates on the cluster dashboard: they are the clearest signals that the metadata layer is in trouble.
End-to-end tracing across Kafka with OpenTelemetry
Metrics tell you that a group is behind; traces tell you which requests are affected and where time is spent. Kafka decouples producers and consumers, so a trace only continues across the topic if the trace context travels inside the message. OpenTelemetry does this with context propagation in Kafka record headers: the producer instrumentation injects the W3C traceparent header, and the consumer instrumentation extracts it.
The OpenTelemetry Java agent instruments the Kafka clients automatically, and instrumentation libraries exist for other languages and clients. The most common reasons for broken traces apply here too: a client library that is not instrumented, a proxy or connector that drops headers, or custom code that creates new records without copying the context.
The OpenTelemetry messaging semantic conventions define how these spans should look. Key points:
- Producer spans use span kind
PRODUCER, consumer spans useCONSUMER. Span names follow the pattern operation plus destination, for examplesend ordersorprocess orders. - Common attributes include
messaging.system(kafka),messaging.destination.name(the topic),messaging.operation.type(for examplesend,receive,process),messaging.consumer.group.name,messaging.destination.partition.idandmessaging.kafka.offset. - Batch consumption uses span links. When a consumer receives or processes many records at once, they usually come from many different traces. Instead of picking one as the parent, the receive or process span carries a link to the context of each message. This keeps every producer trace connected without forcing them into one tree.
- The conventions also define messaging metrics such as
messaging.client.operation.durationandmessaging.process.duration.
The messaging conventions have changed over the last releases, and instrumentation libraries do not all implement the same version. Check which version your instrumentation emits before building dashboards on attribute names. If you need to keep trace volume under control, see our article on tail-based sampling, which lets you keep the slow and failing message flows.
Collecting Kafka metrics with the OpenTelemetry Collector
The OpenTelemetry Collector (contrib distribution) includes a kafkametrics receiver that connects to the cluster as a client and reads broker, topic and consumer group information, including lag. It does not replace JMX broker metrics such as request latency, so combine it with a JMX-based source. A minimal example:
# example configuration, adapt brokers, auth and intervals
receivers:
kafkametrics:
brokers: ["kafka-1:9092", "kafka-2:9092", "kafka-3:9092"]
protocol_version: 2.0.0
scrapers: [brokers, topics, consumers]
collection_interval: 30s
prometheus:
config:
scrape_configs:
- job_name: kafka-jmx # JMX exporter on each broker
static_configs:
- targets: ["kafka-1:7071", "kafka-2:7071", "kafka-3:7071"]
processors:
batch: {}
exporters:
otlphttp:
endpoint: https://otlp.example.com
service:
pipelines:
metrics:
receivers: [kafkametrics, prometheus]
processors: [batch]
exporters: [otlphttp]
The receiver emits metrics such as kafka.consumer_group.lag (per partition), kafka.consumer_group.lag_sum, kafka.partition.replicas_in_sync and kafka.brokers. Option and metric names can change between Collector releases, so verify them against the receiver documentation for your version. Our OpenTelemetry Collector best practices cover memory limits, batching and high availability for the Collector itself.
Example alert rules
The table below is a starting point. All thresholds are example values; derive yours from a few weeks of baseline data and from the freshness your consumers actually need. Page only on what needs a human now, and route the rest to a ticket queue, as described in our guide to reducing alert fatigue.
| Alert | Example condition | Severity (example) |
|---|---|---|
| Offline partitions | OfflinePartitionsCount above 0 for 1 minute | Page |
| Under min ISR | UnderMinIsrPartitionCount above 0 for 2 minutes | Page |
| Under-replicated partitions | UnderReplicatedPartitions above 0 for 10 minutes | Ticket, page if it persists |
| No or multiple active controllers | Cluster sum of ActiveControllerCount not equal to 1 for 1 minute | Page |
| Consumer time lag above target | Estimated time lag above 5 minutes for 10 minutes for a group with a 5 minute freshness target | Page for critical groups |
| Consumer lag growing | Lag sum increased steadily over 30 minutes while produce rate is stable | Ticket |
| Rebalance storm | More than 6 rebalances per hour for a group | Ticket |
| Producer errors | record-error-rate above 0 for 5 minutes | Page if the service is critical |
| Broker request handler saturation | RequestHandlerAvgIdlePercent below 0.3 for 15 minutes | Ticket |
Written as a PromQL-style rule, a growing-lag alert could look like this. Metric names depend on how you collect them; here they follow the Collector receiver after conversion to Prometheus naming.
# example: lag for a consumer group keeps growing for 30 minutes
- alert: KafkaConsumerLagGrowing
expr: |
sum by (group, topic) (kafka_consumer_group_lag_sum) > 10000
and
deriv(sum by (group, topic) (kafka_consumer_group_lag_sum)[30m:1m]) > 0
for: 30m
labels:
severity: ticket
annotations:
summary: "Lag of {{ $labels.group }} on {{ $labels.topic }} is growing"
runbook: "lag-is-growing"
Runbook: consumer lag is growing
A written runbook turns a vague page into a sequence of checks. This one assumes a single consumer group whose lag keeps rising.
- 1. Confirm impact. Is time lag above the freshness target, or is only the offset number large? Check whether downstream users or SLOs are affected.
- 2. Compare in and out. Did the produce rate on the topic increase (a traffic spike, a backfill, a replay), or did the consume rate drop? The answer splits the investigation in two.
- 3. Look per partition. Is the lag spread evenly or concentrated on a few partitions? Concentrated lag points to hot keys, a poison message or one slow consumer instance.
- 4. Check group membership. Are all expected consumers members of the group? Look at rebalance rate, recent deployments, crash loops and
time-between-poll-maxagainstmax.poll.interval.ms. - 5. Check processing time. Open the process spans for the group. Did a downstream dependency (database, HTTP API, cache) get slower? Our guide on debugging latency spikes walks through this step.
- 6. Check errors and retries. Are records failing and being retried in a loop? Look at consumer logs for repeated offsets and at the dead letter topic.
- 7. Check the brokers. Fetch latency, request handler idle ratio, ISR changes and disk on the brokers that lead the lagging partitions.
- 8. Mitigate. Scale consumers up to the number of partitions, skip or park a poison message, roll back a recent change, or temporarily throttle the producer or backfill. Adding partitions changes key to partition mapping, so treat it as a planned change, not an emergency fix.
- 9. Follow up. Record the cause, adjust thresholds if the alert was noisy, and add a dashboard panel for whatever was missing.
Kafka monitoring checklist
Copy this checklist into your platform backlog
- Broker JMX metrics collected from every broker and controller, including host disk, network and JVM GC
- Under-replicated, under min ISR and offline partitions on the cluster dashboard and alerted
- Exactly one active controller verified; KRaft quorum or ZooKeeper ensemble monitored
- Consumer lag collected from outside the consumer, per partition and per group
- Time lag estimated for each important group, with a freshness target written down
- Alerts on growing lag or time lag above target, not on lag above zero
- Partition skew visible: lag and produce rate per partition, owner instance per partition
- Producer error rate, retry rate, request latency and buffer usage collected per service
- Rebalance rate and poll interval metrics collected; cooperative rebalancing and static membership evaluated
- Trace context propagated in message headers; batch consumers use span links
- Messaging semantic convention version known and consistent across services
- Dead letter handling and a retry budget for poison messages
- Runbook for "lag is growing" linked from the alert
How Obseria helps
Obseria is built on OpenTelemetry, so Kafka data arrives the way described above: broker and lag metrics through the OpenTelemetry Collector or Prometheus endpoints, producer and consumer spans from OpenTelemetry instrumentation, and application logs from the same services. See the Kafka monitoring integration and our OpenTelemetry approach for details.
- Logs, metrics and traces are correlated, so you can move from a lag alert to the process spans of the affected group and to the logs of the instance that owns the hottest partition.
- Obseria Pipeline filters, samples and masks telemetry before storage, for example to drop verbose client debug logs or mask personal data in message keys.
- Alerting and SLOs let you express freshness targets for consumer groups instead of fixed offset thresholds.
- Obseria Intelligence investigates incidents such as growing lag and presents a root cause hypothesis together with the evidence it is based on.
To see your Kafka telemetry in Obseria, book a demo.