00:00

Kafka Offset Management

Last updated:

Offset management is how a Kafka consumer group records how far it has read in each partition, so that after a restart or rebalance, consumption continues from the right place. The way you commit offsets decides whether your application may lose records, process some twice, or neither.

The Kafka Offset tutorial introduces what an offset is. This tutorial focuses on managing them: automatic and manual commits, synchronous and asynchronous commits, what happens when no offset exists, and how to move a group to a different position.

1. What Is Offset Management?

A committed offset is the position of the next record a group should read in a partition. If a consumer has processed the record at offset 41, it commits 42. Kafka stores committed offsets in the internal compacted topic __consumer_offsets, keyed by group, topic and partition.

Definition: Offset management is the choice of when and how a consumer commits its position, and how it chooses a start position when no valid committed offset exists.

2. Why It Matters

Commit timingResult after a crashDelivery guarantee
Commit after processingRecords since the last commit are processed againAt-least-once
Commit before processingRecords committed but not processed are skippedAt-most-once
Commit in the same transaction as the outputNeither loss nor duplicates within KafkaExactly-once (Kafka-to-Kafka)

Most applications use at-least-once delivery with idempotent processing.

3. How Offsets Are Committed

Positions in a partitionA partition with records at offsets 0 to 9. The committed offset is 4, so records 0 to 3 are done. The consumer position is 7: records 4 to 6 were returned by poll and are being processed. The log end offset is 10. Lag is 10 minus 4, which is 6. 0 1 2 3 4 5 6 7 8 9 committed = 4 position = 7 log end = 10 processed and committed polled, being processed not yet fetched Lag = log end offset − committed offset = 6. After a crash now, the group restarts at offset 4 and reprocesses 4, 5 and 6.
The committed offset, not the consumer's in-memory position, decides where a group restarts.

3.1 Automatic commits

With enable.auto.commit=true (the default), the consumer commits the offsets returned by the previous poll() every auto.commit.interval.ms (5 seconds), during a later poll() or on close(). Because commits happen inside poll(), records are committed only after your loop has come back for more, which gives at-least-once delivery for simple, synchronous processing. If you process records asynchronously in other threads, auto commit may commit records that are not finished.

3.2 Manual commits

Set enable.auto.commit=false and commit yourself:

  • commitSync() blocks until the broker confirms and retries recoverable errors. It is simple and safe but adds latency.
  • commitAsync() returns immediately and does not retry, because a retry could overwrite a newer commit. Use a callback to log failures.
  • Both accept a Map<TopicPartition, OffsetAndMetadata> to commit specific offsets, for example per record.

3.3 When no committed offset exists

auto.offset.reset decides the start position for a new group, or when the committed offset has been deleted by retention:

ValueBehaviour
latest (default)Start at the end; only new records are read
earliestStart at the oldest retained record
noneThrow NoOffsetForPartitionException
by_duration:<ISO-8601>Start at records newer than the duration, for example by_duration:PT1H (Kafka 4.0+, KIP-1106)

Committed offsets of an empty group are deleted after offsets.retention.minutes (7 days by default).

4. Java Example: Manual Commit After Processing

This consumer writes audit events to a store and commits each batch only after it has been saved.

AuditEventConsumer.java
package com.javabytechie.kafka;

import java.time.Duration;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;

public class AuditEventConsumer {

    public static void main(String[] args) {
        Properties props = new Properties();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        props.put(ConsumerConfig.GROUP_ID_CONFIG, "audit-writer");
        props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());

        TopicPartition partition = new TopicPartition("audit-events", 0);
        try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props)) {
            consumer.subscribe(List.of("audit-events"));
            while (true) {
                ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(500));
                if (records.isEmpty()) {
                    continue;
                }
                for (ConsumerRecord<String, String> r : records) {
                    save(r);
                }
                consumer.commitSync();                      // commit only after the batch is saved
                System.out.println("Committed offset: "
                        + consumer.committed(Set.of(partition)).get(partition).offset());
            }
        }
    }

    static void save(ConsumerRecord<String, String> r) {
        System.out.println("Saved " + r.key() + " (offset " + r.offset() + ")");
    }
}

Output (Kafka 4.4, audit-events topic with 1 partition and three records):

Output
Saved login-u17 (offset 0)
Saved role-change-u17 (offset 1)
Saved logout-u17 (offset 2)
Committed offset: 3

The committed value is 3, the offset of the next record to read, not 2. If the application restarts, it continues at offset 3.

4.1 Spring Boot

In Spring for Apache Kafka the listener container commits offsets, and auto commit on the client is disabled. The default AckMode.BATCH commits after each batch returned by poll() has been processed. For explicit control use MANUAL_IMMEDIATE and an Acknowledgment parameter:

AuditListener.java
package com.javabytechie.kafka;

import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;

@Component
public class AuditListener {

    @KafkaListener(topics = "audit-events", groupId = "audit-writer")
    public void onEvent(String event, Acknowledgment ack) {
        System.out.println("Saving " + event);
        ack.acknowledge();                 // commits this record's offset + 1
    }
}
application.yml
spring:
  kafka:
    listener:
      ack-mode: manual_immediate

4.2 Resetting a group's offsets

To replay or skip data, stop all members of the group and use the CLI. Without --execute the command only shows the plan:

Terminal
bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --group audit-writer \
  --topic audit-events --reset-offsets --to-datetime 2026-11-28T00:00:00.000 --execute

Other options include --to-earliest, --to-latest, --shift-by -100 and --to-offset 500. From code, consumer.seek(partition, offset) moves the position of a running consumer.

5. Common Mistakes

  • Committing record.offset() instead of record.offset() + 1: the last record is processed again after every restart.
  • Auto commit with asynchronous processing: records handed to a thread pool may be committed before they finish.
  • Expecting auto.offset.reset to apply to existing groups: it is used only when no valid committed offset exists.
  • Resetting offsets while consumers are running: the command fails for an active group; stop it first.
  • Calling commitSync() after every record in high-volume topics, which limits throughput.

6. Best Practices

  • Commit after processing and make processing idempotent, for example with upserts or a processed-ID table.
  • Commit per batch, and combine commitAsync() in the loop with commitSync() on shutdown and on revoke.
  • Set auto.offset.reset deliberately for each new group: earliest for full rebuilds, latest for live notifications.
  • Use transactions (sendOffsetsToTransaction) for read-process-write pipelines that must be exactly-once.

7. Conclusion

Committed offsets decide where a consumer group restarts, so commit timing defines your delivery guarantee. Commit after processing for at-least-once delivery, choose auto.offset.reset for new groups on purpose, and use the CLI or seek() to replay data. Read Kafka Consumer Rebalancing to see how commits interact with rebalances.

8. References