Video in progress
What is Kafka consumer lag, and how do you monitor it?
Lag is the difference between the partition's last offset and the offset the consumer group has committed, meaning the number of messages not yet read. If lag keeps growing, the consumer can't keep up with the write rate; I watch it in a metric and alert on the growth trend.
📖 Answer
A CLI for a quick check:
kafka-consumer-groups.sh --bootstrap-server kafka:9092 \
--describe --group billing-service
# TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG
# payments 0 15420 15433 13
# payments 1 9800 48210 38410
In this example one partition has fallen behind. That usually doesn't mean "the consumer is slow"; it's a problem in that specific partition: some key is getting too many messages (a hot key), or there's a poison message in that partition and the consumer is going in circles on one spot.
On prod, export lag as a metric:
- the Kafka client's own metric
records-lag-maxcomes out through Micrometer askafka.consumer.fetch.manager.records.lag.max; - an external exporter (kafka-exporter, Burrow): lag stays visible even when the consumer dies, whereas the client metric disappears along with the consumer.
It's better to alert on the trend and on time, not on the lag number: "lag has been growing for 10 minutes" or "the age of the oldest unread message exceeded 5 minutes". After a nightly batch a lag of 50,000 may be normal, while during the day even 500 is a problem.
First steps when lag grows: are there errors in the consumer log, has processing time gone up (is the DB slow), are rebalances happening often. Adding pods helps only if the partition count allows it.
Sign up to mark studied questions and save your progress.