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
| Setting | Meaning | Default |
group.id | Name of the consumer group | none (required for subscribe) |
auto.offset.reset | What to do when there is no committed offset (or it is out of range): earliest, latest, none | latest |
enable.auto.commit | Commit offsets automatically in the background | true |
max.poll.records | Maximum records returned by one poll() | 500 |
max.poll.interval.ms | Maximum time between two poll() calls before the consumer is considered dead | 300000 (5 min) |
session.timeout.ms, heartbeat.interval.ms | Failure detection through heartbeats | 45000 / 3000 |
fetch.min.bytes, fetch.max.wait.ms | Batching on the broker side for fetches | 1 / 500 |
isolation.level | read_committed hides records from aborted transactions | read_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
| Symptom | Cause and fix |
| Consumer reads nothing | auto.offset.reset=latest and no new data. Use earliest or produce new messages. Check the topic name and group id |
CommitFailedException | The 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 rebalancing | Slow processing, GC pauses or short session timeouts. See the rebalancing lesson |
| Duplicates after restart | At-least-once behaviour. Make the handler idempotent |
SerializationException loops forever on one bad record | A 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.