00:00

Kafka Consumer Lag and Backpressure

Last updated:

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.

Consumer lag in a Kafka partitionA partition log runs from the log start offset 4000 on the left to the log-end offset 9500 on the right. The consumer group's committed offset is 8200. Records between 8200 and 9500 are not yet consumed; the lag is 1300 records. Retention deletes old segments from the left; if retention reaches the committed offset before the consumer does, unread records are lost and the consumer's offset is reset. consumed and committed lag = 1,300 log start 4000 committed 8200 log end 9500 retention deletes from here consumer reads forward producers append here If retention overtakes the committed offset, unread records are gone.
Lag is the distance between the group’s committed offset and the log-end offset. Retention removes data from the other end, so unbounded lag eventually loses data.

2. How to Measure Lag

2.1 From the command line

Terminal
$ 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-max and per-partition records-lag in the consumer-fetch-manager-metrics group, 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

CauseTypical signal
Slow processing (database, HTTP calls, heavy logic)Consumers busy, processing time per record rising
Traffic spike from producersProduce rate higher than consume rate, lag recovers afterwards
Too few consumers or partitionsAll partitions lag evenly; consumers at full CPU
Hot partition from a skewed keyOne 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 partitionOne partition’s committed offset is not moving; error logs repeat
Long GC pauses or memory pressurePoll gaps, GC logs
Slow downstream dependencyRising latency on database or API calls in traces

4. Troubleshooting Steadily Increasing Lag

A practical order of checks in production:

  1. 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.
  2. Did the input rate change? Compare produce rate (broker MessagesInPerSec for the topic) with the consume rate. A new upstream feature may have doubled traffic.
  3. Are offsets moving at all? If CURRENT-OFFSET is frozen, look for a poison pill and retry loops in the logs.
  4. Is the group rebalancing? Look for repeated rebalance logs or CommitFailedException; check max.poll.interval.ms below.
  5. Where is time spent per record? Traces and timers around the handler usually show a slow query or an external call.
  6. 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.bytes and max.partition.fetch.bytes help 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.

WhereMechanism
ConsumerPull model; max.poll.records (default 500) limits each batch; pause()/resume() stop fetching specific partitions while staying in the group
Broker storageUnread data waits in the log, bounded by retention (retention.ms, 7 days by default)
ProducerIf brokers are slow, the producer buffer (buffer.memory, 32 MB) fills and send() blocks for up to max.block.ms, slowing the application down
ClusterClient 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:

BackpressureLoop.java
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:

  1. Shrink the batch: lower max.poll.records so one batch is always processed well within the limit.
  2. Speed up processing: remove the slow call, batch writes, add timeouts to external calls so one hanging request cannot stall the loop.
  3. Raise max.poll.interval.ms when processing is legitimately slow, accepting that a truly stuck consumer is detected later.
  4. Decouple processing with pause/resume and a worker pool as shown above, so poll() is called regularly.
application.yml
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.

11. References