Kafka offsets: where a consumer group resumes

A Kafka consumer group remembers one number per partition, the committed offset, and that number decides which records are lost or repeated after a crash. This page explains the offsets of a partition and runs commit timing, reset policies, seeking by time and resetting a group from outside.

Share

Contents

What an offset is, and which offsets exist

Every record in a Kafka partition has an offset: a 64-bit number, its position in the partition's log. The first record written gets 0, the next 1, and so on. Offsets are never reused, and they belong to one partition: offset 5 in partition 0 and offset 5 in partition 1 are unrelated records.

Kafka keeps no per-message delivery state for consumer groups. Instead, a group remembers one number per partition, the committed offset: the offset of the next record the group should read. Commits are records in the internal, compacted topic __consumer_offsets, written by the group coordinator broker. That design is why Kafka can serve many consumer groups cheaply, and it is also why mistakes with offsets lead to lost or repeated records.

The offsets of a partition, from oldest to newest
OffsetMeaningRead with
Log start offsetThe oldest record still stored; it rises as retention deletes dataAdmin.listOffsets(OffsetSpec.earliest()), consumer.beginningOffsets
Committed offsetWhere the group resumes after a restart or rebalanceconsumer.committed, Admin.listConsumerGroupOffsets
PositionThe next offset this consumer instance will return from poll()consumer.position
Log end offset (high watermark)The offset the next written record will get; consumers can read up to hereOffsetSpec.latest(), consumer.endOffsets

Consumer lag is the log end offset minus the committed offset: how many records the group still has to process. The examples use kafka-clients 4.2.2. Each program starts its own single-node Kafka 4.2 broker inside the JVM first, with EmbeddedKafkaKraftBroker from spring-kafka-test. The offset APIs behave the same against a real cluster, which has three or more brokers.

The four offsets of one partition

A shipment-tracking consumer reads part of a topic, commits, and reads on, so that all four offsets differ. The first two records are deleted first, to move the log start offset:

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.Set;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.OffsetSpec;
import org.apache.kafka.clients.admin.RecordsToDelete;
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 OffsetKinds {

    static final TopicPartition P0 = new TopicPartition("shipments", 0);

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        String servers = broker.getBrokersAsString();
        try (Admin admin = Admin.create(Map.of("bootstrap.servers", servers))) {
            broker.addTopics("shipments");
            try (KafkaProducer<String, String> producer = new KafkaProducer<>(Map.of(
                    "bootstrap.servers", servers,
                    "key.serializer", StringSerializer.class,
                    "value.serializer", StringSerializer.class))) {
                for (int i = 0; i < 10; i++) {
                    producer.send(new ProducerRecord<>("shipments", "parcel-" + i));
                }
            }
            admin.deleteRecords(Map.of(P0, RecordsToDelete.beforeOffset(2))).all().get();

            try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(Map.of(
                    "bootstrap.servers", servers,
                    "group.id", "tracking",
                    "enable.auto.commit", false,
                    "auto.offset.reset", "earliest",
                    "max.poll.records", 4,
                    "key.deserializer", StringDeserializer.class,
                    "value.deserializer", StringDeserializer.class))) {
                consumer.subscribe(List.of("shipments"));
                int read = 0;
                long lastOffset = -1;
                while (read < 4) {
                    for (ConsumerRecord<String, String> r : consumer.poll(Duration.ofSeconds(1))) {
                        read++;
                        lastOffset = r.offset();
                    }
                }
                System.out.println("read 4 records, the last at offset " + lastOffset);
                consumer.commitSync(Map.of(P0, new OffsetAndMetadata(lastOffset + 1)));
                consumer.poll(Duration.ofSeconds(1)); // reads ahead without committing

                long start = admin.listOffsets(Map.of(P0, OffsetSpec.earliest())).all().get()
                        .get(P0).offset();
                long end = admin.listOffsets(Map.of(P0, OffsetSpec.latest())).all().get()
                        .get(P0).offset();
                OffsetAndMetadata committed = consumer.committed(Set.of(P0)).get(P0);
                System.out.println("log start offset     : " + start);
                System.out.println("committed offset     : " + committed.offset());
                System.out.println("consumer position    : " + consumer.position(P0));
                System.out.println("log end offset       : " + end);
                System.out.println("lag (end - committed): " + (end - committed.offset()));
            }
            Map<TopicPartition, OffsetAndMetadata> stored = admin
                    .listConsumerGroupOffsets("tracking").partitionsToOffsetAndMetadata().get();
            System.out.println("Admin sees for group tracking: " + stored.get(P0).offset());
        } finally {
            broker.destroy();
        }
    }

    // Starts a single-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO and prints its storage setup, so both are turned off.
        // 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.OFF);
        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
read 4 records, the last at offset 5
log start offset     : 2
committed offset     : 6
consumer position    : 10
log end offset       : 10
lag (end - committed): 4
Admin sees for group tracking: 6
  • After deleteRecords, the log started at offset 2, so a new group with earliest began there. The fourth record it read was offset 5.
  • The program committed 6, the offset after the last processed record. The committed offset always names the next record to read, never the last one read.
  • The next poll() fetched the remaining records, so the position moved to 10 while the committed offset stayed at 6. If the consumer crashed now, the next one would start at 6 and see offsets 6 to 9 again.
  • The log end offset was 10, and the lag was 10 - 6 = 4 records.
  • The Admin client saw the same committed offset, 6. Monitoring tools compute lag this way, from outside the group.

Commits are kept for offsets.retention.minutes, 7 days by default, after a group becomes empty. A group that stays away longer loses its offsets and starts again according to auto.offset.reset.

When to commit: lost records and duplicates

The moment of the commit decides what a crash costs. Three consumers process invoices, each committing at a different time, and each crashes while processing the fourth invoice. A new instance in the same group then takes over:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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 CommitTiming {

    static String servers;

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        servers = broker.getBrokersAsString();
        try {
            broker.addTopics("invoices");
            try (KafkaProducer<String, String> producer = new KafkaProducer<>(Map.of(
                    "bootstrap.servers", servers,
                    "key.serializer", StringSerializer.class,
                    "value.serializer", StringSerializer.class))) {
                for (int i = 0; i < 6; i++) {
                    producer.send(new ProducerRecord<>("invoices", "inv-" + i));
                }
            }
            // each strategy crashes while processing inv-3, then a new instance starts
            for (String strategy : List.of("commit-before", "commit-after", "commit-offset")) {
                List<String> processed = new ArrayList<>();
                try {
                    run(strategy, processed, true);
                } catch (IllegalStateException crash) {
                    System.out.println(strategy + ": crashed at inv-3, processed " + processed);
                }
                List<String> again = new ArrayList<>();
                run(strategy, again, false);
                System.out.println(strategy + ": restart processed " + again);
            }
        } finally {
            broker.destroy();
        }
    }

    static void run(String strategy, List<String> processed, boolean crash) {
        Map<String, Object> props = new HashMap<>();
        props.put("bootstrap.servers", servers);
        props.put("group.id", strategy);
        props.put("enable.auto.commit", false);
        props.put("auto.offset.reset", "earliest");
        props.put("key.deserializer", StringDeserializer.class);
        props.put("value.deserializer", StringDeserializer.class);
        try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props)) {
            consumer.subscribe(List.of("invoices"));
            long quietSince = System.currentTimeMillis();
            while (System.currentTimeMillis() - quietSince < 2000) {
                var records = consumer.poll(Duration.ofMillis(200));
                if (consumer.assignment().isEmpty() || !records.isEmpty()) {
                    quietSince = System.currentTimeMillis();
                }
                if (strategy.equals("commit-before") && !records.isEmpty()) {
                    consumer.commitSync(); // the position is already past the whole batch
                }
                for (ConsumerRecord<String, String> r : records) {
                    if (crash && r.value().equals("inv-3")) {
                        throw new IllegalStateException("crash"); // no further commits
                    }
                    processed.add(r.value());
                    TopicPartition tp = new TopicPartition(r.topic(), r.partition());
                    if (strategy.equals("commit-after")) {
                        consumer.commitSync(Map.of(tp, new OffsetAndMetadata(r.offset() + 1)));
                    } else if (strategy.equals("commit-offset")) {
                        // a classic mistake: the committed offset should be the NEXT record
                        consumer.commitSync(Map.of(tp, new OffsetAndMetadata(r.offset())));
                    }
                }
            }
        }
    }

    // Starts a single-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO and prints its storage setup, so both are turned off.
        // 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.OFF);
        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
commit-before: crashed at inv-3, processed [inv-0, inv-1, inv-2]
commit-before: restart processed []
commit-after: crashed at inv-3, processed [inv-0, inv-1, inv-2]
commit-after: restart processed [inv-3, inv-4, inv-5]
commit-offset: crashed at inv-3, processed [inv-0, inv-1, inv-2]
commit-offset: restart processed [inv-2, inv-3, inv-4, inv-5]
  • commit-before: committing right after poll() stored offset 6, the end of the batch, before any invoice was processed. After the crash, the restart processed nothing: inv-3, inv-4 and inv-5 were lost. This is at-most-once delivery.
  • commit-after: committing offset + 1 after each invoice stored 3 when inv-2 was done. The restart began at inv-3 and nothing was lost or repeated. With a crash after processing but before the commit, that one record would be processed twice: this is at-least-once delivery.
  • commit-offset: committing r.offset() instead of r.offset() + 1 stored 2 after inv-2. The restart processed inv-2 a second time. This off-by-one mistake repeats one record per partition at every restart.

At-least-once is the usual choice, together with processing that tolerates a repeat, for example by writing with the record's key or offset as a unique id. Committing after every record, as here, is clear but slow, because each commitSync waits for the broker. Committing once per batch, after the whole batch is processed, keeps the same guarantee with far fewer requests. Auto-commit also commits inside poll(), for the records returned by the previous poll, so it is at-least-once as long as processing finishes before the next poll. Exactly-once needs Kafka transactions, with the offsets committed inside the producer's transaction; see Kafka transactions.

commitSync retries until it succeeds or hits a fatal error. commitAsync does not wait and does not retry, because a retried old commit could overwrite a newer one. A common pattern is commitAsync in the loop and one commitSync before close().

Where a new group starts: auto.offset.reset

A group with no committed offset, or with one that points to deleted data, starts according to auto.offset.reset. The sensor topic holds one reading per hour for the last five hours, with timestamps set by the producer, so that the time-based options give predictable answers:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
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 ResetAndSeek {

    static final TopicPartition P0 = new TopicPartition("sensor", 0);
    static final long HOUR = 3600000L;
    static String servers;

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        servers = broker.getBrokersAsString();
        try {
            broker.addTopics("sensor");
            long now = System.currentTimeMillis();
            try (KafkaProducer<String, String> producer = new KafkaProducer<>(Map.of(
                    "bootstrap.servers", servers,
                    "key.serializer", StringSerializer.class,
                    "value.serializer", StringSerializer.class))) {
                for (int i = 0; i < 6; i++) { // one reading per hour, the last one now
                    int hoursAgo = 5 - i;
                    producer.send(new ProducerRecord<>("sensor", 0, now - hoursAgo * HOUR,
                            null, hoursAgo + "h ago"));
                }
            }
            for (String reset : List.of("earliest", "latest", "by_duration:PT2H30M", "none")) {
                try (KafkaConsumer<String, String> c = consumer("group-" + reset, reset)) {
                    c.subscribe(List.of("sensor"));
                    ConsumerRecords<String, String> records = ConsumerRecords.empty();
                    while (c.assignment().isEmpty()) {
                        records = c.poll(Duration.ofMillis(200));
                    }
                    if (records.isEmpty()) {
                        records = c.poll(Duration.ofSeconds(1));
                    }
                    String first = records.isEmpty()
                            ? "no record yet, position " + c.position(P0)
                            : "first record at offset " + records.iterator().next().offset()
                                    + ": \"" + records.iterator().next().value() + "\"";
                    System.out.printf("%-20s -> %s%n", reset, first);
                } catch (RuntimeException e) {
                    System.out.printf("%-20s -> %s%n", reset, e.getClass().getSimpleName());
                }
            }

            // a seek by time: the first record at or after 3.5 hours ago
            try (KafkaConsumer<String, String> c = consumer(null, "earliest")) {
                c.assign(List.of(P0));
                OffsetAndTimestamp found = c.offsetsForTimes(
                        Map.of(P0, now - 3 * HOUR - HOUR / 2)).get(P0);
                c.seek(P0, found.offset());
                String value = c.poll(Duration.ofSeconds(2)).iterator().next().value();
                System.out.println("offsetsForTimes(3.5 h ago) -> offset " + found.offset()
                        + ", value \"" + value + "\"");
                OffsetAndTimestamp future = c.offsetsForTimes(Map.of(P0, now + HOUR)).get(P0);
                System.out.println("offsetsForTimes(1 h from now) -> " + future);
            }
        } finally {
            broker.destroy();
        }
    }

    static KafkaConsumer<String, String> consumer(String group, String reset) {
        Map<String, Object> props = new HashMap<>();
        props.put("bootstrap.servers", servers);
        if (group != null) {
            props.put("group.id", group);
        }
        props.put("auto.offset.reset", reset);
        props.put("key.deserializer", StringDeserializer.class);
        props.put("value.deserializer", StringDeserializer.class);
        return new KafkaConsumer<>(props);
    }

    // Starts a single-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO and prints its storage setup, so both are turned off.
        // 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.OFF);
        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
earliest             -> first record at offset 0: "5h ago"
latest               -> no record yet, position 6
by_duration:PT2H30M  -> first record at offset 3: "2h ago"
none                 -> NoOffsetForPartitionException
offsetsForTimes(3.5 h ago) -> offset 2, value "3h ago"
offsetsForTimes(1 h from now) -> null
  • earliest started at offset 0, the oldest reading.
  • latest, the default, started at position 6, the end of the log, and saw nothing: only records written after the group started would arrive.
  • by_duration:PT2H30M, added by KIP-1106 and supported by the 4.2 client used here, started at the first record no older than two and a half hours: offset 3, the reading from 2 hours ago.
  • none made poll() throw NoOffsetForPartitionException. This suits applications that must never guess where to start.
  • offsetsForTimes found offset 2 as the first record at or after 3.5 hours ago, and a seek to it returned the reading from 3 hours ago. For a time later than the newest record, it returned null.

The reset also applies when a committed offset is out of range, for example after retention deleted the records it pointed to. With latest, such a consumer silently skips everything between its old position and the end of the log, which is why many teams prefer earliest for business data. The latest default has a second trap: when partitions are added to a topic, records written to them before the group notices the new partitions are skipped.

Changing a group's offsets from outside

After a bug fix, a team often wants to reprocess some data, which means moving the group's committed offset back. The Admin API does this, as does kafka-consumer-groups.sh --reset-offsets, which uses the same calls:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import org.apache.kafka.clients.admin.Admin;
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 AdminOffsets {

    static final TopicPartition P0 = new TopicPartition("reports", 0);
    static String servers;

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        servers = broker.getBrokersAsString();
        try (Admin admin = Admin.create(Map.of("bootstrap.servers", servers))) {
            broker.addTopics("reports");
            try (KafkaProducer<String, String> producer = new KafkaProducer<>(Map.of(
                    "bootstrap.servers", servers,
                    "key.serializer", StringSerializer.class,
                    "value.serializer", StringSerializer.class))) {
                for (int i = 0; i < 6; i++) {
                    producer.send(new ProducerRecord<>("reports", "report-" + i));
                }
            }
            System.out.println("first run read : " + readAll());
            System.out.println("group offset   : " + groupOffset(admin));

            // rewind the group, e.g. after fixing a bug in the report code
            admin.alterConsumerGroupOffsets("billing",
                    Map.of(P0, new OffsetAndMetadata(3))).all().get();
            System.out.println("after reset    : " + groupOffset(admin));
            System.out.println("next run read  : " + readAll());

            // the same change while a member of the group is running
            try (KafkaConsumer<String, String> active = consumer()) {
                active.subscribe(List.of("reports"));
                while (active.assignment().isEmpty()) {
                    active.poll(Duration.ofMillis(200));
                }
                try {
                    admin.alterConsumerGroupOffsets("billing",
                            Map.of(P0, new OffsetAndMetadata(0))).all().get();
                } catch (ExecutionException e) {
                    System.out.println("reset while active: "
                            + e.getCause().getClass().getSimpleName());
                }
            }
            admin.deleteConsumerGroupOffsets("billing", Set.of(P0)).all().get();
            System.out.println("after delete   : " + groupOffset(admin));
        } finally {
            broker.destroy();
        }
    }

    static Object groupOffset(Admin admin) throws Exception {
        OffsetAndMetadata o = admin.listConsumerGroupOffsets("billing")
                .partitionsToOffsetAndMetadata().get().get(P0);
        return o == null ? "none" : o.offset();
    }

    static KafkaConsumer<String, String> consumer() {
        return new KafkaConsumer<>(Map.of(
                "bootstrap.servers", servers,
                "group.id", "billing",
                "auto.offset.reset", "earliest",
                "key.deserializer", StringDeserializer.class,
                "value.deserializer", StringDeserializer.class));
    }

    // reads until 2 quiet seconds have passed; close() commits the position
    static List<String> readAll() {
        List<String> seen = new ArrayList<>();
        try (KafkaConsumer<String, String> consumer = consumer()) {
            consumer.subscribe(List.of("reports"));
            long quietSince = System.currentTimeMillis();
            while (System.currentTimeMillis() - quietSince < 2000) {
                for (ConsumerRecord<String, String> r : consumer.poll(Duration.ofMillis(200))) {
                    seen.add(r.value());
                    quietSince = System.currentTimeMillis();
                }
                if (consumer.assignment().isEmpty()) {
                    quietSince = System.currentTimeMillis();
                }
            }
        }
        return seen;
    }

    // Starts a single-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO and prints its storage setup, so both are turned off.
        // 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.OFF);
        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
first run read : [report-0, report-1, report-2, report-3, report-4, report-5]
group offset   : 6
after reset    : 3
next run read  : [report-3, report-4, report-5]
reset while active: UnknownMemberIdException
after delete   : none
  • The first run read all six reports, and closing the consumer committed offset 6.
  • alterConsumerGroupOffsets set it to 3 while no consumer was running. The next run started at report-3, as intended.
  • The same call while a member was active failed with UnknownMemberIdException. The broker refuses outside changes to the offsets of a group with active members, because the members would overwrite them with their next commit. Stop all consumers of the group first.
  • deleteConsumerGroupOffsets removed the committed offset completely; the next start would follow auto.offset.reset.

The command-line tool adds conveniences on top, such as --to-datetime, --shift-by and --dry-run, which prints the new offsets without applying them. Use the dry run first: a reset is easy to get wrong across many partitions.

Storing offsets with the results

When a consumer writes its results to a database, there is a stronger option than committing to Kafka: store the offset in the same database transaction as the result, and tell the consumer where to start. A ledger adds deposits to a balance, stops after two of four as if it had crashed, and is started again:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Duration;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
import org.apache.kafka.clients.consumer.ConsumerRecord;
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.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 OffsetsInDatabase {

    static String servers;

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        servers = broker.getBrokersAsString();
        try (Connection db = DriverManager.getConnection("jdbc:h2:mem:bank")) {
            try (Statement s = db.createStatement()) {
                s.execute("create table balance (account varchar primary key, cents int)");
                s.execute("insert into balance values ('acct-1', 0)");
                s.execute("create table kafka_offset (topic varchar, part int, next bigint,"
                        + " primary key (topic, part))");
            }
            db.setAutoCommit(false);
            broker.addTopics("deposits");
            try (KafkaProducer<String, String> producer = new KafkaProducer<>(Map.of(
                    "bootstrap.servers", servers,
                    "key.serializer", StringSerializer.class,
                    "value.serializer", StringSerializer.class))) {
                for (int cents : new int[] {100, 250, 50, 600}) {
                    producer.send(new ProducerRecord<>("deposits", "acct-1", "" + cents));
                }
            }
            run(db, 2); // processes two deposits, then "crashes"
            System.out.println("after the crash: " + state(db));
            run(db, Integer.MAX_VALUE);
            System.out.println("after a restart: " + state(db));
        } finally {
            broker.destroy();
        }
    }

    // reads deposits; each one updates the balance AND the offset in one DB transaction
    static void run(Connection db, int limit) throws Exception {
        try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(Map.of(
                "bootstrap.servers", servers,
                "group.id", "ledger",
                "enable.auto.commit", false, // Kafka never stores this group's offsets
                "key.deserializer", StringDeserializer.class,
                "value.deserializer", StringDeserializer.class))) {
            consumer.subscribe(List.of("deposits"), new ConsumerRebalanceListener() {
                @Override
                public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
                    for (TopicPartition tp : partitions) {
                        long next = storedOffset(db, tp);
                        System.out.println("assigned " + tp + ", seeking to stored offset "
                                + next);
                        consumer.seek(tp, next);
                    }
                }

                @Override
                public void onPartitionsRevoked(Collection<TopicPartition> partitions) {
                }
            });
            int processed = 0;
            while (true) {
                for (ConsumerRecord<String, String> r : consumer.poll(Duration.ofSeconds(1))) {
                    if (processed == limit) {
                        return; // stop without any commit to Kafka
                    }
                    try (PreparedStatement add = db.prepareStatement(
                            "update balance set cents = cents + ? where account = ?");
                         PreparedStatement offset = db.prepareStatement(
                            "merge into kafka_offset key (topic, part) values (?, ?, ?)")) {
                        add.setInt(1, Integer.parseInt(r.value()));
                        add.setString(2, r.key());
                        add.executeUpdate();
                        offset.setString(1, r.topic());
                        offset.setInt(2, r.partition());
                        offset.setLong(3, r.offset() + 1);
                        offset.executeUpdate();
                        db.commit(); // both changes, or neither
                    }
                    processed++;
                }
                if (!consumer.assignment().isEmpty() && remaining(consumer) == 0) {
                    return;
                }
            }
        }
    }

    static int remaining(KafkaConsumer<String, String> consumer) {
        TopicPartition tp = new TopicPartition("deposits", 0);
        return (int) (consumer.endOffsets(List.of(tp)).get(tp) - consumer.position(tp));
    }

    static long storedOffset(Connection db, TopicPartition tp) {
        try (PreparedStatement q = db.prepareStatement(
                "select next from kafka_offset where topic = ? and part = ?")) {
            q.setString(1, tp.topic());
            q.setInt(2, tp.partition());
            try (ResultSet rs = q.executeQuery()) {
                return rs.next() ? rs.getLong(1) : 0;
            }
        } catch (SQLException e) {
            throw new IllegalStateException(e);
        }
    }

    static String state(Connection db) throws SQLException {
        try (Statement s = db.createStatement();
             ResultSet rs = s.executeQuery(
                     "select b.cents, o.next from balance b, kafka_offset o")) {
            rs.next();
            return "balance " + rs.getInt(1) + " cents, stored next offset " + rs.getLong(2);
        }
    }

    // Starts a single-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO and prints its storage setup, so both are turned off.
        // 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.OFF);
        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
assigned deposits-0, seeking to stored offset 0
after the crash: balance 350 cents, stored next offset 2
assigned deposits-0, seeking to stored offset 2
after a restart: balance 1000 cents, stored next offset 4
  • Each deposit updated the balance and the stored offset in one H2 transaction, so the two can never disagree. After the crash the balance was 350 cents (100 + 250) and the stored next offset was 2.
  • The group never committed anything to Kafka (enable.auto.commit=false and no commit calls). On assignment, the ConsumerRebalanceListener read the offset from the database and called seek.
  • The restart began at offset 2 and added 50 and 600, for a final balance of 1000 cents: every deposit counted exactly once, even though the consumer stopped in the middle.

This is exactly-once processing into a database without Kafka transactions. It needs a store with transactions, and the seek must happen in onPartitionsAssigned, so that it also runs when a rebalance moves the partition to another instance. Kafka-side lag monitoring then shows nothing useful for the group, because Kafka holds no committed offsets for it; committing to Kafka as well, after the database commit, keeps the tools working.

Choosing a commit strategy

Requirements and the offset handling that fits
RequirementApproach
Simple consumers, duplicates acceptableAuto-commit (the default), processing finished before the next poll()
No lost recordsenable.auto.commit=false, commit offset + 1 after processing
No lost records, high throughputCommit once per batch, commitAsync in the loop, commitSync on close
Results written to Kafka exactly onceTransactions with sendOffsetsToTransaction
Results written to a database exactly onceStore the offset in the same database transaction, and seek to it on assignment
A new group must process historyauto.offset.reset=earliest, or by_duration for a recent window
Reprocess after a bug fixStop the group, reset with Admin or kafka-consumer-groups.sh

Related pages: Kafka consumers, rebalancing, where offsets must be committed before partitions move, lag monitoring and transactions.