Kafka Consumer Lag and Backpressure
Kafka consumer lag is the number of records a consumer group still has to read in a partition: the distance between the newest record and the group’s committed position. A small, stable lag is normal. A lag that keeps growing means consumers cannot keep up, and if it grows past the topic’s retention, unread data is deleted. Because Kafka consumers pull data at their own pace, lag is also how backpressure shows up in Kafka.
This article explains how lag is calculated, how to measure it, how to find the root cause when it keeps increasing, how Kafka handles backpressure, and how to fix rebalances caused by exceeding max.poll.interval.ms.
1. What Is Consumer Lag?
For each partition, lag is calculated as:
lag = log-end offset − committed offset of the consumer group
The log-end offset is the offset the next produced record will get; the committed offset is where the group will resume. Lag is measured in records, not time. A lag of 10,000 is nothing for a topic receiving 50,000 records per second and serious for one receiving 10 per minute, so also track how long the oldest unread record has been waiting.
2. How to Measure Lag
2.1 From the command line
$ bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group invoice-service
GROUP TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG CONSUMER-ID HOST CLIENT-ID
invoice-service orders 0 182340 182355 15 consumer-1-7c2… /10.0.1.12 consumer-1
invoice-service orders 1 179902 179910 8 consumer-1-7c2… /10.0.1.12 consumer-1
invoice-service orders 2 120417 188650 68233 consumer-2-a91… /10.0.1.13 consumer-2
Here only partition 2 is behind, which points to that consumer or that partition, not the whole group.
2.2 From metrics
- Consumer client:
records-lag-maxand per-partitionrecords-lagin theconsumer-fetch-manager-metricsgroup, available through JMX or Micrometer in Spring Boot. - External lag exporters that read committed offsets and log-end offsets from the cluster, so lag is visible even when the consumer is down.
- Alert on the trend, such as lag growing for 10 minutes or estimated time-to-catch-up above a limit, not on a fixed number.
3. Why Lag Grows: Root Causes
| Cause | Typical signal |
|---|---|
| Slow processing (database, HTTP calls, heavy logic) | Consumers busy, processing time per record rising |
| Traffic spike from producers | Produce rate higher than consume rate, lag recovers afterwards |
| Too few consumers or partitions | All partitions lag evenly; consumers at full CPU |
| Hot partition from a skewed key | One partition lags, others are fine |
| Frequent rebalances | “Revoking/Assigned partitions” log lines repeating; throughput drops to zero during each one |
| A failing record blocking a partition | One partition’s committed offset is not moving; error logs repeat |
| Long GC pauses or memory pressure | Poll gaps, GC logs |
| Slow downstream dependency | Rising latency on database or API calls in traces |
4. Troubleshooting Steadily Increasing Lag
A practical order of checks in production:
- Is it all partitions or a few? Use
kafka-consumer-groups.sh --describe. A few partitions point to hot keys, a stuck record or one unhealthy instance; all partitions point to capacity or a shared dependency. - Did the input rate change? Compare produce rate (broker
MessagesInPerSecfor the topic) with the consume rate. A new upstream feature may have doubled traffic. - Are offsets moving at all? If
CURRENT-OFFSETis frozen, look for a poison pill and retry loops in the logs. - Is the group rebalancing? Look for repeated rebalance logs or
CommitFailedException; check max.poll.interval.ms below. - Where is time spent per record? Traces and timers around the handler usually show a slow query or an external call.
- Are all consumers active? Members without partitions mean more consumers than partitions; instances missing from the group mean crashes.
5. How to Reduce Lag
- Make processing cheaper: batch database writes, cache reference data, remove per-record remote calls, and use batch listeners where it fits.
- Add consumers up to the number of partitions; beyond that, extra consumers stay idle.
- Add partitions if consumers are already at one per partition, remembering that this changes the key-to-partition mapping.
- Process in parallel by key inside a consumer when partitions cannot be added; see Kafka Message Ordering.
- Fix hot keys by choosing a more evenly distributed key where ordering allows it.
- Handle poison pills with a dead letter topic instead of endless retries; see Retry Mechanism in Apache Kafka.
- Tune fetching only after the above: larger
fetch.min.bytesandmax.partition.fetch.byteshelp throughput when records are small and processing is cheap.
6. How Kafka Handles Backpressure
Kafka handles backpressure differently from push-based brokers. Consumers pull records when they are ready, so a slow consumer never gets overwhelmed with data it did not ask for. The excess simply stays in the partition log on the brokers’ disks, which is designed to hold days of data. Backpressure therefore becomes lag rather than memory exhaustion or dropped messages.
| Where | Mechanism |
|---|---|
| Consumer | Pull model; max.poll.records (default 500) limits each batch; pause()/resume() stop fetching specific partitions while staying in the group |
| Broker storage | Unread data waits in the log, bounded by retention (retention.ms, 7 days by default) |
| Producer | If brokers are slow, the producer buffer (buffer.memory, 32 MB) fills and send() blocks for up to max.block.ms, slowing the application down |
| Cluster | Client quotas limit the byte rate of producers and consumers so one client cannot overload brokers |
When a consumer hands work to an internal queue or a slow downstream system, it should apply backpressure itself: pause the partitions when the queue is full and resume them when it drains. Polling continues, so the consumer stays in the group:
BlockingQueue<ConsumerRecord<String, String>> work = new ArrayBlockingQueue<>(2_000);
while (running) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(200));
records.forEach(work::add); // fits: we only poll while there is room
if (work.remainingCapacity() < 500 && consumer.paused().isEmpty()) {
consumer.pause(consumer.assignment()); // stop fetching, keep heartbeating via poll()
} else if (work.size() < 500 && !consumer.paused().isEmpty()) {
consumer.resume(consumer.paused());
}
commitCompletedOffsets(consumer); // commit only what workers have finished
}
The queue capacity check works because max.poll.records is 500 by default: the consumer only polls while at least 500 slots are free. In Spring for Apache Kafka, the listener container offers pause()/resume() and pausing by partition for the same purpose.
7. Rebalances Caused by max.poll.interval.ms
Scenario: processing a batch takes longer than max.poll.interval.ms (default 5 minutes). The consumer’s background heartbeat keeps the session alive, but because poll() was not called in time, the client leaves the group. The partitions are reassigned, the old member’s commit fails with CommitFailedException, the batch is processed again elsewhere, and the cycle repeats. Lag grows and duplicates appear.
Signals: a warning in the client log that the poll timeout has expired and the consumer is leaving the group, frequent rebalances in the group coordinator logs, and CommitFailedExceptions.
Fixes, in order of preference:
- Shrink the batch: lower
max.poll.recordsso one batch is always processed well within the limit. - Speed up processing: remove the slow call, batch writes, add timeouts to external calls so one hanging request cannot stall the loop.
- Raise
max.poll.interval.mswhen processing is legitimately slow, accepting that a truly stuck consumer is detected later. - Decouple processing with pause/resume and a worker pool as shown above, so
poll()is called regularly.
spring:
kafka:
consumer:
max-poll-records: 100 # smaller batches: each poll loop finishes sooner
properties:
max.poll.interval.ms: 600000 # only if processing is legitimately slow
More on rebalance triggers and timeouts is in Consumer Rebalancing.
8. Best Practices
- Monitor lag per partition and per group, with alerts on growth and on time-to-catch-up.
- Keep retention comfortably longer than the longest consumer outage you must survive.
- Plan partitions for peak consumer parallelism, not average load.
- Put timeouts on every external call in a consumer.
- Use a DLT for poison pills so one record cannot freeze a partition.
- Load-test consumers at peak rates, including rebalances during load.
9. Summary
Consumer lag is the log-end offset minus the committed offset, per partition. Measure it with kafka-consumer-groups.sh and client metrics, and troubleshoot growing lag by checking whether all or only some partitions lag, whether input traffic changed, whether offsets move, and whether the group is rebalancing. Kafka’s pull model turns backpressure into lag that waits in the log, bounded by retention; consumers can apply their own backpressure with pause()/resume(). Rebalances caused by max.poll.interval.ms are fixed by smaller batches, faster processing, or a higher limit.
10. Related Reading
- Kafka Performance Tuning: Throughput and Latency
- Kafka Message Ordering and Concurrent Processing
- Consumer Rebalancing
11. References
- Apache Kafka 4.4: Basic operations (checking consumer position)
- Apache Kafka 4.4: Consumer configs (max.poll.interval.ms, max.poll.records)
- Apache Kafka 4.4 Javadoc: KafkaConsumer (consumption flow control, pause and resume)
- Apache Kafka 4.4: Monitoring (consumer fetch metrics)
- Spring for Apache Kafka: Pausing and resuming listener containers
Kafka Consumer Lag and Backpressure Interview Questions and Answers
Common interview questions on Kafka Consumer Lag and Backpressure, from basic to scenario-based, with short answers you can explain in your own words.
Basic questions
Q. What is consumer lag in Kafka, and how is it calculated?
Answer: Consumer lag is how far a consumer group is behind the newest data in a partition: the log-end offset minus the group’s committed offset. It is measured per partition and summed for the topic or group. Lag is a count of records, so it should be read together with the produce rate; estimated time-to-catch-up is often a better alerting signal than the raw number.
Q. How do you check consumer lag in production?
Answer: On the command line, kafka-consumer-groups.sh --describe --group <group> shows the current offset, log-end offset and lag per partition, plus which member owns each partition. For monitoring, use the consumer metrics records-lag-max and per-partition records-lag (via JMX or Micrometer), or an external lag exporter that reads offsets from the cluster, which keeps working when the consumer itself is down.
Intermediate questions
Q. How does Kafka handle backpressure when consumers cannot keep up with producers?
Answer: Consumers pull data, so they are never pushed more than they ask for; the backlog stays in the partition log on the brokers and appears as lag, bounded by the topic’s retention. Consumers control their intake with max.poll.records and can stop fetching specific partitions with pause(), then resume() later, while still calling poll() to stay in the group. On the producer side, a full buffer.memory makes send() block up to max.block.ms, and broker quotas cap client byte rates.
Q. Why is lag that approaches the topic’s retention period dangerous?
Answer: Retention deletes old segments regardless of whether a consumer has read them. If the group’s committed offset falls behind the log start offset, those records are gone for that group, and on its next fetch the offset is out of range, so auto.offset.reset decides where it continues: earliest skips the deleted gap, latest skips everything up to now. Both are silent data loss for that consumer, which is why lag alerts should fire long before this point.
Tricky and scenario questions
Q. Consumer lag keeps increasing in production. How do you find the root cause and fix it?
Answer: First, look at lag per partition: if only a few partitions lag, suspect a hot key, a poison pill blocking a partition (offset not moving, repeated errors), or one unhealthy instance. If all partitions lag, compare produce and consume rates to see whether traffic rose, then look for rebalances and at time spent per record (slow database or remote calls). Fix the cause: send poison pills to a DLT, optimise or batch processing, add consumers up to the partition count, add partitions or key-based parallelism, and stop rebalances by tuning max.poll.records and max.poll.interval.ms.
Q. A consumer takes longer than max.poll.interval.ms to process a batch, causing frequent rebalances. How do you troubleshoot and resolve it?
Answer: Confirm it in the logs: a poll-timeout warning followed by the member leaving the group, rebalances, and CommitFailedException when the old member tries to commit. Then measure batch processing time against the limit. Reduce max.poll.records so a batch finishes comfortably in time, remove or time-limit slow calls, and raise max.poll.interval.ms only if the work is legitimately slow. For very slow work, process on worker threads and pause partitions while the workers are busy, so poll() keeps running.
Q. You doubled the number of consumer instances, but lag did not improve. Why might that be?
Answer: The group may already have one consumer per partition, so the new instances get no partitions and stay idle. Or the bottleneck is not the consumers: a shared database or external API is saturated, a hot partition carries most of the traffic, or a stuck record blocks one partition. Adding instances also triggers rebalances, which pause consumption briefly. Check the partition assignment and per-partition lag before scaling further.