Kafka consumer lag monitoring

Consumer lag is the distance between what has been written to a partition and what a consumer group has processed. It is the most useful single signal for a Kafka application, and it is easy to measure wrongly. This page explains how lag is defined, then measures it four ways against a broker running inside each program and publishes it to Prometheus through Micrometer.

Share

Contents

What consumer lag is

Each partition is a log with a log end offset: the offset the next written record will get. A consumer group stores, per partition, a committed offset: the offset of the next record it will process. The lag of the group on that partition is the difference:

Text
lag = log end offset - committed offset

Lag of 0 means the group has processed everything written so far. Lag that stays at a few hundred is normal for a busy topic, because records arrive between two commits. Lag that keeps growing means the group processes slower than producers write, or has stopped. Because a stopped consumer reports nothing itself, lag measured from outside the application is one of the few signals that catches a consumer that crashed, hangs, or was never deployed.

There are several ways to get the two numbers:

Ways to measure consumer lag
SourceMeasured byBest for
Admin API: listConsumerGroupOffsets and listOffsetsAny process with cluster accessMonitoring jobs and exporters, works for stopped groups
kafka-consumer-groups.sh --describeA shell on any machineChecking a group by hand
Consumer metrics records-lag, records-lag-maxThe consumer itselfDashboards per instance; silent when the consumer stops
Time lag: age of the next unprocessed recordA job that also reads one recordAlerts in seconds or minutes, comparable across topics
External services: Burrow, Prometheus exporters, vendor toolsA separate serviceFleet-wide lag with history and evaluation rules

Each program starts its own single-node KRaft broker in the JVM with EmbeddedKafkaKraftBroker from spring-kafka-test; a real cluster has 3 or more brokers. The programs use the plain Kafka 4.2.2 client and tool classes.

Lag from committed and end offsets

This is what every lag tool computes underneath. A topic with three partitions gets 10 records in each, and a group processes 7 records of partition 0, 4 of partition 1 and none of partition 2:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.ListOffsetsResult.ListOffsetsResultInfo;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.admin.OffsetSpec;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;

public class LagFromOffsets {

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        String bootstrap = broker.getBrokersAsString();
        try (Admin admin = Admin.create(Map.<String, Object>of("bootstrap.servers", bootstrap))) {
            admin.createTopics(List.of(new NewTopic("orders", 3, (short) 1))).all().get();
            try (KafkaProducer<String, String> producer = new KafkaProducer<>(
                    Map.of("bootstrap.servers", bootstrap),
                    new StringSerializer(), new StringSerializer())) {
                for (int i = 0; i < 30; i++) {
                    producer.send(new ProducerRecord<>("orders", i % 3, null, "order-" + i));
                }
            }
            // the group processes 7 records from partition 0 and 4 from partition 1,
            // and never commits anything for partition 2
            try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(Map.of(
                    "bootstrap.servers", bootstrap, "group.id", "billing",
                    "enable.auto.commit", "false", "auto.offset.reset", "earliest"),
                    new StringDeserializer(), new StringDeserializer())) {
                consumer.assign(List.of(tp(0), tp(1)));
                Map<TopicPartition, Long> done = new TreeMap<>((a, b) -> a.partition()
                        - b.partition());
                while (done.getOrDefault(tp(0), 0L) < 7 || done.getOrDefault(tp(1), 0L) < 4) {
                    for (ConsumerRecord<String, String> r : consumer.poll(Duration.ofMillis(500))) {
                        TopicPartition p = tp(r.partition());
                        if (r.offset() < (p.partition() == 0 ? 7 : 4)) {
                            done.put(p, r.offset() + 1);
                        }
                    }
                }
                consumer.commitSync(done.entrySet().stream().collect(Collectors.toMap(
                        Map.Entry::getKey, e -> new OffsetAndMetadata(e.getValue()))));
            }

            Map<TopicPartition, OffsetAndMetadata> committed = admin
                    .listConsumerGroupOffsets("billing").partitionsToOffsetAndMetadata().get();
            Map<TopicPartition, OffsetSpec> latestSpec = Map.of(tp(0), OffsetSpec.latest(),
                    tp(1), OffsetSpec.latest(), tp(2), OffsetSpec.latest());
            Map<TopicPartition, ListOffsetsResultInfo> latest =
                    admin.listOffsets(latestSpec).all().get();
            long total = 0;
            for (int p = 0; p < 3; p++) {
                long end = latest.get(tp(p)).offset();
                OffsetAndMetadata c = committed.get(tp(p));
                String lag = c == null ? "unknown (no commit)" : String.valueOf(end - c.offset());
                total += c == null ? 0 : end - c.offset();
                System.out.println("orders-" + p + ": end offset " + end + ", committed "
                        + (c == null ? "-" : c.offset()) + ", lag " + lag);
            }
            System.out.println("total lag of committed partitions: " + total);
        } finally {
            broker.destroy();
        }
    }

    static TopicPartition tp(int partition) {
        return new TopicPartition("orders", partition);
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.ERROR);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
orders-0: end offset 10, committed 7, lag 3
orders-1: end offset 10, committed 4, lag 6
orders-2: end offset 10, committed -, lag unknown (no commit)
total lag of committed partitions: 9
  • Partition 0 has 10 records and a committed offset of 7, so the lag is 3: offsets 7, 8 and 9 are waiting.
  • Partition 1 lags by 6, for the same reason.
  • Partition 2 has no committed offset at all, so its lag is not defined. Tools differ here: some show it as unknown, some count the whole partition, and some leave it out, which hides a partition nobody consumes. Where the group would start depends on auto.offset.reset.
  • The total over committed partitions is 9. Totals are useful for dashboards, but alert per partition too: one stuck partition can hide behind a small total.

Both calls are cheap, so a monitoring job can run them every few seconds for many groups. listConsumerGroupOffsets accepts several groups in one request, and listOffsets takes all partitions at once. The committed offset only moves when the group commits, so with auto-commit every 5 seconds, the lag seen from outside jumps in steps.

kafka-consumer-groups.sh

The command-line tool shows the same numbers, plus which member owns each partition. The program runs the tool's Java class while a consumer is active, after it has closed, and with --state:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.common.utils.Exit;
import org.apache.kafka.tools.consumer.group.ConsumerGroupCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;

public class ConsumerGroupsTool {

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        String bootstrap = broker.getBrokersAsString();
        // the tool calls System.exit when it finishes; Kafka's own tests swap that out
        Exit.setExitProcedure((code, message) -> { });
        System.setErr(System.out); // the tool prints notes to stderr; keep them in order
        try (Admin admin = Admin.create(Map.<String, Object>of("bootstrap.servers", bootstrap))) {
            admin.createTopics(List.of(new NewTopic("orders", 2, (short) 1))).all().get();
            try (KafkaProducer<String, String> producer = new KafkaProducer<>(
                    Map.of("bootstrap.servers", bootstrap),
                    new StringSerializer(), new StringSerializer())) {
                for (int i = 0; i < 20; i++) {
                    producer.send(new ProducerRecord<>("orders", i % 2, null, "order-" + i));
                }
            }
            try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(Map.of(
                    "bootstrap.servers", bootstrap, "group.id", "billing",
                    "client.id", "billing-1", "max.poll.records", "6",
                    "auto.offset.reset", "earliest", "enable.auto.commit", "false"),
                    new StringDeserializer(), new StringDeserializer())) {
                consumer.subscribe(List.of("orders"));
                int read = 0;
                while (read < 6) {
                    read += consumer.poll(Duration.ofMillis(500)).count();
                }
                consumer.commitSync();
                System.out.println("$ kafka-consumer-groups.sh --describe --group billing"
                        + "   (consumer running)");
                ConsumerGroupCommand.main(new String[] {"--bootstrap-server", bootstrap,
                    "--describe", "--group", "billing"});
            }
            System.out.println();
            System.out.println("$ kafka-consumer-groups.sh --describe --group billing"
                    + "   (consumer closed)");
            ConsumerGroupCommand.main(new String[] {"--bootstrap-server", bootstrap,
                "--describe", "--group", "billing"});
            System.out.println();
            System.out.println("$ kafka-consumer-groups.sh --describe --group billing --state");
            ConsumerGroupCommand.main(new String[] {"--bootstrap-server", bootstrap,
                "--describe", "--group", "billing", "--state"});
        } finally {
            Exit.resetExitProcedure();
            broker.destroy();
        }
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.ERROR);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
$ kafka-consumer-groups.sh --describe --group billing   (consumer running)

GROUP           TOPIC           PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             CONSUMER-ID                                    HOST            CLIENT-ID
billing         orders          0          6               10              4               billing-1-7ffe77d2-8c8f-4b59-8bda-b978c2d38aee /127.0.0.1      billing-1
billing         orders          1          0               10              10              billing-1-7ffe77d2-8c8f-4b59-8bda-b978c2d38aee /127.0.0.1      billing-1

$ kafka-consumer-groups.sh --describe --group billing   (consumer closed)

Consumer group 'billing' has no active members.

GROUP           TOPIC           PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             CONSUMER-ID     HOST            CLIENT-ID
billing         orders          0          6               10              4               -               -               -
billing         orders          1          0               10              10              -               -               -

$ kafka-consumer-groups.sh --describe --group billing --state

Consumer group 'billing' has no active members.

GROUP           COORDINATOR (ID)          ASSIGNMENT-STRATEGY  STATE                #MEMBERS
billing         localhost:42589  (0)      -                    Empty                0
  • While the consumer ran, both partitions belonged to billing-1. The CONSUMER-ID is the client id plus a random suffix that changes on every run, and HOST is the member's address.
  • CURRENT-OFFSET is the committed offset, LOG-END-OFFSET the end of the partition, and LAG their difference: 4 for partition 0, where the consumer read 6 of 10 records, and 10 for partition 1, where it read none but committed its starting position, 0.
  • After the consumer closed, the tool printed "has no active members", and the member columns show -. The offsets and the lag are still there, because they are stored on the broker, not in the consumer.
  • --state shows the group coordinator broker (its port differs on every run), the assignment strategy, the state Empty and 0 members. A group that should be running but is Empty is an incident even when its lag is still small.

Use --all-groups to list every group at once, and --members --verbose to see the assignment per member. The tool exits the JVM when it finishes; the program replaces that with Exit.setExitProcedure, as Kafka's own tests do.

Lag in time, not records

A lag of 500 records says little by itself: on a topic with a thousand records per second it is half a second, on a topic with one record per hour it is three weeks. The age of the next unprocessed record answers the question people actually ask, "how far behind are we?". The program creates two groups with different record lag and computes both measures:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.admin.OffsetSpec;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;

public class TimeLag {

    static final TopicPartition CLICKS = new TopicPartition("clicks", 0);
    static final TopicPartition INVOICES = new TopicPartition("invoices", 0);

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        String bootstrap = broker.getBrokersAsString();
        // record timestamps are set relative to now, so the ages printed are stable
        long now = System.currentTimeMillis();
        try (Admin admin = Admin.create(Map.<String, Object>of("bootstrap.servers", bootstrap));
                KafkaProducer<String, String> producer = new KafkaProducer<>(
                        Map.of("bootstrap.servers", bootstrap),
                        new StringSerializer(), new StringSerializer())) {
            admin.createTopics(List.of(new NewTopic("clicks", 1, (short) 1),
                    new NewTopic("invoices", 1, (short) 1))).all().get();
            // clicks: 1,000 records, one every 60 ms over the last minute
            for (int i = 0; i < 1000; i++) {
                producer.send(new ProducerRecord<>("clicks", 0, now - 60000 + i * 60L, null,
                        "click-" + i));
            }
            // invoices: 10 records, one every 30 minutes over the last 5 hours
            for (int i = 0; i < 10; i++) {
                producer.send(new ProducerRecord<>("invoices", 0, now - 18000000 + i * 1800000L,
                        null, "invoice-" + i));
            }
            producer.flush();

            // both groups are 500 or 5 records behind
            admin.alterConsumerGroupOffsets("clicks-app",
                    Map.of(CLICKS, new OffsetAndMetadata(500))).all().get();
            admin.alterConsumerGroupOffsets("invoice-app",
                    Map.of(INVOICES, new OffsetAndMetadata(5))).all().get();

            report(admin, bootstrap, "clicks-app", CLICKS, now);
            report(admin, bootstrap, "invoice-app", INVOICES, now);
        } finally {
            broker.destroy();
        }
    }

    // record lag from offsets, time lag from the timestamp of the next unprocessed record
    static void report(Admin admin, String bootstrap, String group, TopicPartition tp,
            long now) throws Exception {
        long committed = admin.listConsumerGroupOffsets(group).partitionsToOffsetAndMetadata()
                .get().get(tp).offset();
        long end = admin.listOffsets(Map.of(tp, OffsetSpec.latest())).all().get().get(tp)
                .offset();
        long timestamp;
        try (KafkaConsumer<String, String> peek = new KafkaConsumer<>(Map.of(
                "bootstrap.servers", bootstrap, "max.poll.records", "1"),
                new StringDeserializer(), new StringDeserializer())) {
            peek.assign(List.of(tp));
            peek.seek(tp, committed);
            ConsumerRecord<String, String> next = null;
            while (next == null) {
                var records = peek.poll(Duration.ofMillis(500));
                next = records.isEmpty() ? null : records.iterator().next();
            }
            timestamp = next.timestamp();
        }
        System.out.printf("%-12s lag %3d records, next record waiting %s%n", group,
                end - committed, Duration.ofMillis(now - timestamp));
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.ERROR);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
clicks-app   lag 500 records, next record waiting PT30S
invoice-app  lag   5 records, next record waiting PT2H30M
  • clicks-app lags by 500 records, which looks bad, but the oldest unprocessed click is only 30 seconds old, because clicks arrive every 60 ms.
  • invoice-app lags by only 5 records, which looks fine, but the next invoice has waited 2 hours and 30 minutes, because invoices arrive every 30 minutes.
  • The waiting time comes from the timestamp of the record at the committed offset, read with a separate consumer that uses assign and seek, so the group itself is not disturbed.

Time lag needs one fetch per partition, so a monitoring job usually computes it less often than record lag, or estimates it from the record lag and the recent write rate, which is how Burrow-style tools evaluate a group. It depends on producers setting meaningful timestamps: with message.timestamp.type=CreateTime, the default, a producer that sends old timestamps makes the lag look larger than it is.

Transactions and the last stable offset

Transactional producers make lag harder to read. A commit or abort writes a control record, a marker that takes an offset but is never delivered to consumers. A read_committed consumer also cannot read past the last stable offset (LSO), the first offset of the oldest open transaction. This program writes five one-record transactions, then leaves a sixth open:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.ListOffsetsOptions;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.admin.OffsetSpec;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.IsolationLevel;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;

public class TransactionLag {

    static final TopicPartition TP = new TopicPartition("payments", 0);

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        String bootstrap = broker.getBrokersAsString();
        try (Admin admin = Admin.create(Map.<String, Object>of("bootstrap.servers", bootstrap));
                KafkaProducer<String, String> producer = new KafkaProducer<>(Map.of(
                        "bootstrap.servers", bootstrap, "transactional.id", "payments-tx"),
                        new StringSerializer(), new StringSerializer());
                KafkaConsumer<String, String> consumer = new KafkaConsumer<>(Map.of(
                        "bootstrap.servers", bootstrap, "group.id", "ledger",
                        "isolation.level", "read_committed", "auto.offset.reset", "earliest",
                        "enable.auto.commit", "false"),
                        new StringDeserializer(), new StringDeserializer())) {
            admin.createTopics(List.of(new NewTopic("payments", 1, (short) 1))).all().get();
            producer.initTransactions();
            for (int i = 0; i < 5; i++) { // five transactions of one record each
                producer.beginTransaction();
                producer.send(new ProducerRecord<>("payments", "payment-" + i));
                producer.commitTransaction();
            }

            consumer.subscribe(List.of("payments"));
            read(consumer, 5);
            report(admin, "all 5 committed records processed");

            producer.beginTransaction(); // a transaction that stays open
            producer.send(new ProducerRecord<>("payments", "payment-5"));
            producer.flush();
            System.out.println("records read while the transaction is open: "
                    + consumer.poll(Duration.ofSeconds(2)).count());
            report(admin, "one transaction left open");

            producer.commitTransaction();
            read(consumer, 1);
            report(admin, "after the commit");
        } finally {
            broker.destroy();
        }
    }

    static void read(KafkaConsumer<String, String> consumer, int count) {
        int seen = 0;
        while (seen < count) {
            seen += consumer.poll(Duration.ofMillis(500)).count();
        }
        consumer.commitSync();
    }

    static void report(Admin admin, String label) throws Exception {
        long committed = admin.listConsumerGroupOffsets("ledger")
                .partitionsToOffsetAndMetadata().get().get(TP).offset();
        long logEnd = admin.listOffsets(Map.of(TP, OffsetSpec.latest())).all().get().get(TP)
                .offset();
        long stable = admin.listOffsets(Map.of(TP, OffsetSpec.latest()),
                new ListOffsetsOptions(IsolationLevel.READ_COMMITTED)).all().get().get(TP)
                .offset();
        System.out.println(label + ":");
        System.out.println("  committed " + committed + ", log end " + logEnd
                + ", last stable " + stable);
        System.out.println("  lag against log end " + (logEnd - committed)
                + ", against last stable offset " + (stable - committed));
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.ERROR);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
all 5 committed records processed:
  committed 10, log end 10, last stable 10
  lag against log end 0, against last stable offset 0
records read while the transaction is open: 0
one transaction left open:
  committed 10, log end 11, last stable 10
  lag against log end 1, against last stable offset 0
after the commit:
  committed 12, log end 12, last stable 12
  lag against log end 0, against last stable offset 0
  • Five records took ten offsets, one record and one commit marker each. The consumer's position moved past the last marker, so the committed offset is 10 and the lag is 0. Offsets count records plus markers, so record lag on a transactional topic overstates the number of records waiting.
  • With a transaction open, the log end moved to 11, but the LSO stayed at 10. The consumer read nothing for 2 seconds, yet the usual lag calculation shows 1. Measured against the LSO, the lag is 0: there is nothing the consumer is allowed to read.
  • After the commit, the consumer read the record, its position moved past the new marker to 12, and both measures returned to 0.

A transaction that stays open, for example because its producer hangs, blocks every read_committed consumer of the partition until transaction.timeout.ms aborts it. Lag against the log end grows, lag against the LSO stays flat, and the consumer looks healthy while it waits. For topics written transactionally, track both: listOffsets with new ListOffsetsOptions(IsolationLevel.READ_COMMITTED) returns the LSO. A growing gap between log end and LSO points at a stuck producer, not a slow consumer; the transactions deep dive shows how to find and abort it.

Exporting lag to Prometheus with Micrometer

Dashboards and alerts usually read lag from a monitoring system such as Prometheus, which fetches a plain-text page of metrics from each target every few seconds. The program publishes both kinds of lag through one Micrometer PrometheusMeterRegistry (from micrometer-registry-prometheus 1.17.2) and serves it at /metrics. A group reads 12 of 20 records in partition 0 and 3 of 20 in partition 1, then commits, so the expected lag is 8 and 17:

Java
import ch.qos.logback.classic.Level;
import com.sun.net.httpserver.HttpServer;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.binder.kafka.KafkaClientMetrics;
import io.micrometer.prometheusmetrics.PrometheusConfig;
import io.micrometer.prometheusmetrics.PrometheusMeterRegistry;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.admin.OffsetSpec;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;

public class LagPrometheus {

    static final TopicPartition P0 = new TopicPartition("orders", 0);
    static final TopicPartition P1 = new TopicPartition("orders", 1);

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        String bootstrap = broker.getBrokersAsString();
        PrometheusMeterRegistry registry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
        HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
        server.createContext("/metrics", exchange -> {
            byte[] body = registry.scrape().getBytes(StandardCharsets.UTF_8);
            exchange.getResponseHeaders().set("Content-Type",
                    "text/plain; version=0.0.4; charset=utf-8");
            exchange.sendResponseHeaders(200, body.length);
            try (OutputStream out = exchange.getResponseBody()) {
                out.write(body);
            }
        });
        server.start();
        URI metricsUri = URI.create("http://localhost:" + server.getAddress().getPort()
                + "/metrics");

        try (Admin admin = Admin.create(Map.<String, Object>of("bootstrap.servers", bootstrap))) {
            admin.createTopics(List.of(new NewTopic("orders", 2, (short) 1))).all().get();
            try (KafkaProducer<String, String> producer = new KafkaProducer<>(
                    Map.of("bootstrap.servers", bootstrap),
                    new StringSerializer(), new StringSerializer())) {
                for (int i = 0; i < 40; i++) {
                    producer.send(new ProducerRecord<>("orders", i % 2, null, "order-" + i));
                }
            }

            // 1. lag computed outside the consumer from the Admin API, as an exporter does
            for (TopicPartition tp : List.of(P0, P1)) {
                Gauge.builder("kafka.consumergroup.lag", admin, a -> groupLag(a, tp))
                        .description("Log end offset minus committed offset")
                        .tags("group", "billing", "topic", tp.topic(),
                                "partition", String.valueOf(tp.partition()))
                        .register(registry);
            }

            KafkaConsumer<String, String> consumer = new KafkaConsumer<>(Map.of(
                    "bootstrap.servers", bootstrap, "group.id", "billing",
                    "client.id", "billing-1", "enable.auto.commit", "false",
                    "auto.offset.reset", "earliest", "max.poll.records", "1"),
                    new StringDeserializer(), new StringDeserializer());
            consumer.assign(List.of(P0, P1));
            readFrom(consumer, P0, P1, 12); // 12 records of partition 0
            readFrom(consumer, P1, P0, 3);  // then 3 records of partition 1
            consumer.commitSync(Map.of(P0, new OffsetAndMetadata(consumer.position(P0)),
                    P1, new OffsetAndMetadata(consumer.position(P1))));

            // 2. the consumer's own metrics, bound as Spring Boot binds them
            KafkaClientMetrics binder = new KafkaClientMetrics(consumer);
            binder.bindTo(registry);

            HttpClient http = HttpClient.newHttpClient();
            scrape(http, metricsUri, "while the consumer runs");

            binder.close();
            consumer.close();
            scrape(http, metricsUri, "after the consumer closed");
        } finally {
            server.stop(0);
            broker.destroy();
        }
    }

    // polls one partition while the other is paused, until n records were returned
    static void readFrom(KafkaConsumer<String, String> consumer, TopicPartition read,
            TopicPartition paused, int n) {
        consumer.resume(List.of(read));
        consumer.pause(List.of(paused));
        int count = 0;
        while (count < n) {
            count += consumer.poll(Duration.ofMillis(200)).count();
        }
    }

    static double groupLag(Admin admin, TopicPartition tp) {
        try {
            OffsetAndMetadata committed = admin.listConsumerGroupOffsets("billing")
                    .partitionsToOffsetAndMetadata().get().get(tp);
            long end = admin.listOffsets(Map.of(tp, OffsetSpec.latest())).partitionResult(tp)
                    .get().offset();
            return committed == null ? Double.NaN : end - committed.offset();
        } catch (Exception e) {
            return Double.NaN;
        }
    }

    // fetches /metrics over HTTP, as Prometheus does, and prints the lag lines
    static void scrape(HttpClient http, URI uri, String when) throws Exception {
        HttpResponse<String> response = http.send(HttpRequest.newBuilder(uri).build(),
                HttpResponse.BodyHandlers.ofString());
        List<String> lines = response.body().lines().toList();
        System.out.println("GET /metrics " + when + ": " + response.statusCode() + ", "
                + response.headers().firstValue("Content-Type").orElse("") + ", "
                + lines.size() + " lines");
        for (String line : lines) {
            if (line.contains("consumergroup_lag") || line.contains("records_lag")) {
                // Kafka's HELP texts are long: print the start of them only
                System.out.println("  " + (line.startsWith("# HELP") && line.length() > 90
                        ? line.substring(0, 87) + "..." : line));
            }
        }
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.ERROR);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1);
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
GET /metrics while the consumer runs: 200, text/plain; version=0.0.4; charset=utf-8, 351 lines
  # HELP kafka_consumer_fetch_manager_records_lag The latest lag of the partition. Note: ...
  # TYPE kafka_consumer_fetch_manager_records_lag gauge
  kafka_consumer_fetch_manager_records_lag{client_id="billing-1",kafka_version="4.2.2",partition="0",topic="orders"} 8.0
  kafka_consumer_fetch_manager_records_lag{client_id="billing-1",kafka_version="4.2.2",partition="1",topic="orders"} 17.0
  # HELP kafka_consumer_fetch_manager_records_lag_avg The average lag of the partition. N...
  # TYPE kafka_consumer_fetch_manager_records_lag_avg gauge
  kafka_consumer_fetch_manager_records_lag_avg{client_id="billing-1",kafka_version="4.2.2",partition="0",topic="orders"} 13.5
  kafka_consumer_fetch_manager_records_lag_avg{client_id="billing-1",kafka_version="4.2.2",partition="1",topic="orders"} 18.0
  # HELP kafka_consumer_fetch_manager_records_lag_max The max lag of the partition. Note:...
  # TYPE kafka_consumer_fetch_manager_records_lag_max gauge
  kafka_consumer_fetch_manager_records_lag_max{client_id="billing-1",kafka_version="4.2.2",partition="0",topic="orders"} 19.0
  kafka_consumer_fetch_manager_records_lag_max{client_id="billing-1",kafka_version="4.2.2",partition="1",topic="orders"} 19.0
  # HELP kafka_consumergroup_lag Log end offset minus committed offset
  # TYPE kafka_consumergroup_lag gauge
  kafka_consumergroup_lag{group="billing",partition="0",topic="orders"} 8.0
  kafka_consumergroup_lag{group="billing",partition="1",topic="orders"} 17.0
GET /metrics after the consumer closed: 200, text/plain; version=0.0.4; charset=utf-8, 4 lines
  # HELP kafka_consumergroup_lag Log end offset minus committed offset
  # TYPE kafka_consumergroup_lag gauge
  kafka_consumergroup_lag{group="billing",partition="0",topic="orders"} 8.0
  kafka_consumergroup_lag{group="billing",partition="1",topic="orders"} 17.0
  • The program fetched the page over HTTP, as Prometheus does, and got the text exposition format, version=0.0.4. Each meter becomes a # HELP line, a # TYPE line and one sample per tag combination.
  • kafka_consumergroup_lag is the gauge the program registered itself. Each scrape calls listConsumerGroupOffsets and listOffsets, so the values are the Admin API lag from the first section: 8 and 17. This is how lag exporters work.
  • kafka_consumer_fetch_manager_records_lag comes from the consumer's own metric records-lag, bound with Micrometer's KafkaClientMetrics. Micrometer replaced the dots and dashes with underscores, and the Kafka tags became the labels client_id, partition and topic, plus kafka_version. It also shows 8 and 17, because the consumer's position matched the committed offset.
  • records_lag_max is 19 for both partitions: the lag right after the first record of each was read. records_lag_avg is the average over the samples in the current window, for example 13.5 for partition 0, halfway between 19 and 8.
  • The page had 351 lines while the consumer ran, nearly all of them consumer metrics. After the consumer closed and its binder was closed, as Spring Kafka does for the consumers it creates, all client lag series were gone. Only the 4 lines of the Admin-based gauge were left, still at 8 and 17.

The last scrape is the reason to export lag from outside the application: a crashed consumer takes its own lag metric with it, and in Prometheus that series simply stops, which an alert on high lag does not notice. A rule such as kafka_consumergroup_lag > 1000 keeps working. A real exporter runs as its own service, discovers all groups with listGroups, and caches the results so that a scrape does not send requests for every partition. Spring Boot Actuator serves the same registry at /actuator/prometheus.

Alerting on lag

A fixed threshold on record lag is the most common lag alert and the most often wrong one. Better rules combine a few signals:

  • Growth, not size: alert when lag has grown over a window, such as 10 minutes, rather than when it passes a number. A busy topic can carry a large, stable lag safely.
  • Time lag for service levels: if records must be processed within 5 minutes, alert on the age of the oldest unprocessed record, which maps directly to that promise.
  • Group state: alert when a group that should run is Empty, or when its member count drops, whatever the lag.
  • Committed offset not moving: a group whose committed offsets stay the same while the log end moves has stopped making progress, even if it is still a member.
  • Per partition: one partition stuck behind a poison record, while the others are fine, is a common failure and disappears in group totals.

Monitoring lag from one external process also scales better than collecting records-lag-max from every consumer, and keeps working when consumers are down. The consumer metrics remain useful to see which instance is slow; they are shown on Kafka monitoring.

Choosing a lag measurement

Questions and the measurement that answers them
QuestionMeasurement
Is this group keeping up?Record lag per partition from the Admin API, watched for growth
How late is our processing, in minutes?Age of the record at the committed offset
Is anyone consuming at all?Group state and member count from describeConsumerGroups
Which instance is slow?Consumer metric records-lag-max per client id
A quick look during an incidentkafka-consumer-groups.sh --describe --group ...
Transactional topicsLag against both the log end and the last stable offset
Many teams and hundreds of groupsA central exporter or Burrow-style service with history

How committed offsets are stored and reset is covered on Kafka offsets, and how a consumer's poll loop and rebalances affect them on the Kafka consumer and Kafka rebalancing. When lag comes from slow processing, Kafka performance tuning shows the settings that matter.