Kafka Offset Management
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.
2. Why It Matters
| Commit timing | Result after a crash | Delivery guarantee |
|---|---|---|
| Commit after processing | Records since the last commit are processed again | At-least-once |
| Commit before processing | Records committed but not processed are skipped | At-most-once |
| Commit in the same transaction as the output | Neither loss nor duplicates within Kafka | Exactly-once (Kafka-to-Kafka) |
Most applications use at-least-once delivery with idempotent processing.
3. How Offsets Are Committed
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:
| Value | Behaviour |
|---|---|
latest (default) | Start at the end; only new records are read |
earliest | Start at the oldest retained record |
none | Throw 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.
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):
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:
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
}
}
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:
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 ofrecord.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.resetto 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 withcommitSync()on shutdown and on revoke. - Set
auto.offset.resetdeliberately for each new group:earliestfor full rebuilds,latestfor 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
Kafka Offset Management Interview Questions and Answers
Common interview questions on Kafka Offset Management, from basic to scenario-based, with short answers you can explain in your own words.
Basic questions
Q. How often should a consumer commit offsets?
Answer: Often enough that a restart repeats little work, but not so often that commits slow the consumer. Committing once per batch returned by poll() is the usual balance; committing synchronously after every record adds a broker round trip per record and limits throughput. If a batch takes long to process, commit specific offsets every few hundred records or every few seconds. Remember that the amount of reprocessing after a crash equals the work done since the last successful commit.
Q. How do Spring Kafka ack modes BATCH, RECORD and MANUAL_IMMEDIATE differ?
Answer: They decide when the listener container commits. BATCH (the default) commits once after all records from a poll have been processed, which is efficient. RECORD commits after each record, which reduces reprocessing but costs throughput. MANUAL and MANUAL_IMMEDIATE commit only after your code calls Acknowledgment.acknowledge(); the first queues the commit for the end of the batch, the second commits at once. With manual modes, every record must eventually be acknowledged or handled by the error handler.
Intermediate questions
Q. How do you commit offsets safely when records are processed in a thread pool?
Answer: A partition’s offset may only advance past records that are completely processed, so track completion per partition and commit the highest offset below which every record is done, not simply the latest one. Keep the commit on the polling thread, because KafkaConsumer is not thread-safe. If workers fall behind, call pause() on the busy partitions and keep polling so the consumer stays in the group, then resume() them. On revocation, wait for in-flight work for those partitions before committing.
Q. Can you store extra information with a committed offset?
Answer: Yes. OffsetAndMetadata takes an optional metadata string that is stored with the offset in __consumer_offsets, for example the ID of the last processed batch or the instance that committed it. consumer.committed(...) returns it again after a restart, which helps with debugging and simple bookkeeping. It is not a replacement for a database: keep it small, and store real processing state with your output.
Tricky and scenario questions
Q. How do you reset the offset of only one partition?
Answer: Stop the group, then name the partition after the topic in kafka-consumer-groups.sh, for example --topic orders:2 --reset-offsets --to-offset 500 --execute; several partitions can be listed as orders:0,2. Run it with --dry-run first. From code, use seek(new TopicPartition("orders", 2), 500) and commit, which moves only that partition.
Q. What causes a CommitFailedException, and how do you handle it?
Answer: The group coordinator rejects a commit when the consumer no longer owns the partitions, usually because it exceeded max.poll.interval.ms and was removed from the group, so a rebalance happened in the meantime. The records it processed will be delivered again to the new owner. Do not retry the commit; log it, make processing idempotent, and fix the cause: smaller batches (max.poll.records), faster processing, or a longer poll interval.