Kafka Consumer API in Java: poll Loop, Consumer Groups and Offsets

Apache Kafka 17 min min read Updated: Nov 17, 2026 Beginner
Kafka Consumer API in Java: poll Loop, Consumer Groups and Offsets
Beginner Topic 1 of 4

Consumers Pull Data

Kafka consumers pull records from brokers in a loop. This lets each consumer control its speed and position. A consumer joins a consumer group using group.id. Kafka divides the topic's partitions among the members of the group.

text Topic "orders" (3 partitions), group "email-service": 1 consumer -> reads P0, P1, P2 2 consumers -> C1 reads P0,P1 C2 reads P2 3 consumers -> one partition each 4 consumers -> one consumer is idle (never more active consumers than partitions) A second group "analytics" reads the same topic independently with its own offsets.

A Complete Consumer

java import org.apache.kafka.clients.consumer.*; import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.errors.WakeupException; import java.time.Duration; import java.util.List; import java.util.Properties; public class EmailConsumer { public static void main(String[] args) { Properties props = new Properties(); props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(ConsumerConfig.GROUP_ID_CONFIG, "email-service"); props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); // where to start if the group has no saved offset props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false"); // we commit manually after processing KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props); final Thread mainThread = Thread.currentThread(); // graceful shutdown: Ctrl+C -> wakeup() makes poll() throw WakeupException Runtime.getRuntime().addShutdownHook(new Thread(() -> { consumer.wakeup(); try { mainThread.join(); } catch (InterruptedException ignored) {} })); try { consumer.subscribe(List.of("orders")); while (true) { ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(500)); for (ConsumerRecord<String, String> r : records) { System.out.printf("p=%d offset=%d key=%s value=%s%n", r.partition(), r.offset(), r.key(), r.value()); sendEmail(r.value()); // your business logic } if (!records.isEmpty()) consumer.commitSync(); // mark everything from this poll as processed } } catch (WakeupException e) { // expected on shutdown } finally { consumer.close(); // leaves the group cleanly (fast rebalance) } } static void sendEmail(String json) { /* ... */ } }

Key Settings

SettingMeaningDefault
group.idName of the consumer groupnone (required for subscribe)
auto.offset.resetWhat to do when there is no committed offset (or it is out of range): earliest, latest, nonelatest
enable.auto.commitCommit offsets automatically in the backgroundtrue
max.poll.recordsMaximum records returned by one poll()500
max.poll.interval.msMaximum time between two poll() calls before the consumer is considered dead300000 (5 min)
session.timeout.ms, heartbeat.interval.msFailure detection through heartbeats45000 / 3000
fetch.min.bytes, fetch.max.wait.msBatching on the broker side for fetches1 / 500
isolation.levelread_committed hides records from aborted transactionsread_uncommitted
auto.offset.reset only matters at the start: If the group already has a committed offset, the consumer continues from there and ignores auto.offset.reset. To reread data, reset the group's offsets or use a new group.id.

What Is an Offset Commit?

Committing an offset means: "this group has processed everything before offset N in this partition". Kafka stores it in the topic __consumer_offsets. After a restart or rebalance, the consumer continues at the committed offset.

text Partition 0: [0][1][2][3][4][5][6][7] ^ committed offset = 4 (records 0..3 are done) Consumer crashes after processing 4 and 5 but before committing -> restarts at 4 -> processes 4 and 5 AGAIN => default behaviour is "at-least-once": no loss, possible duplicates (make processing idempotent)

Where to Read From: assign and seek

java // subscribe: group manages partitions. assign: you choose partitions, no group rebalancing TopicPartition tp = new TopicPartition("orders", 0); consumer.assign(List.of(tp)); consumer.seek(tp, 1000); // start at offset 1000 consumer.seekToBeginning(List.of(tp)); consumer.seekToEnd(List.of(tp)); // start from a timestamp Map<TopicPartition, Long> query = Map.of(tp, System.currentTimeMillis() - 3600_000); Map<TopicPartition, OffsetAndTimestamp> res = consumer.offsetsForTimes(query); consumer.seek(tp, res.get(tp).offset());

Common Problems

SymptomCause and fix
Consumer reads nothingauto.offset.reset=latest and no new data. Use earliest or produce new messages. Check the topic name and group id
CommitFailedExceptionThe consumer was removed from the group (took longer than max.poll.interval.ms) before committing. Process faster, lower max.poll.records or raise the interval
Constant rebalancingSlow processing, GC pauses or short session timeouts. See the rebalancing lesson
Duplicates after restartAt-least-once behaviour. Make the handler idempotent
SerializationException loops forever on one bad recordA poison message. Handle with an error-handling deserializer and a dead-letter topic (see error handling lesson)
The consumer is not thread-safe: Use one KafkaConsumer per thread. If you need parallel processing, run several consumers (one per thread) in the same group, or hand records to a worker pool and commit carefully.

Conclusion

A consumer subscribes to topics with a group.id, calls poll() in a loop, processes records and commits offsets. Kafka assigns partitions among group members. Commit after processing for at-least-once behaviour, and shut down with wakeup() and close().

Quick Summary: poll loop; group.id; commit after processing; auto.offset.reset only without committed offset; one consumer per thread.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators