Kafka consumers: the poll loop and its rules
A Kafka consumer pulls records with poll(), and that one call also keeps its group membership alive and commits its offsets. This page explains what poll() does, then runs the loop, a clean shutdown, assign and seek, fetch tuning and the two traps that break consumers: shared threads and slow processing.
Contents
How a Kafka consumer reads
A Kafka consumer pulls records from brokers. The broker never pushes anything: the application calls poll()
Behind poll()
- Group membership: a consumer with a
joins a consumer group. The group coordinator, one of the brokers, assigns each partition of the subscribed topics to exactly one member, and reassigns them when members join or leave (a rebalance).group.id - Fetching: the client sends fetch requests to the leader of each assigned partition and keeps the answers in a buffer, so that most
calls return data already in memory.poll() - Liveness: heartbeats tell the coordinator the member is alive, and the time between
calls tells it the member is still making progress.poll() - Offset commits: by default, the position is committed to the group every 5 seconds, from inside
, and onpoll() .close()
A KafkaConsumerwakeup()
| Method | Partitions chosen by | Commits | Best for |
|---|---|---|---|
subscribe(topics) | The group coordinator, with rebalancing | To the group | Services that scale out and survive failures |
assign(partitions) | The application | Optional; needs a group.id | Tools, replays, tests and stream processors that manage their own state |
The examples use kafka-clientsEmbeddedKafkaKraftBrokerspring-kafka-teststartBroker
The poll loop and a clean shutdown
A mailer service reads welcome mails from a topic until it is told to stop. The usual way to stop a consumer is wakeup()
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.concurrent.CountDownLatch;
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.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.errors.WakeupException;
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 PollLoop {
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
broker.addTopics("emails");
try (KafkaProducer<String, String> producer = new KafkaProducer<>(Map.of(
"bootstrap.servers", broker.getBrokersAsString(),
"key.serializer", StringSerializer.class,
"value.serializer", StringSerializer.class))) {
for (int i = 1; i <= 5; i++) {
producer.send(new ProducerRecord<>("emails", "user-" + i, "welcome mail " + i));
}
}
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(Map.of(
ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, broker.getBrokersAsString(),
ConsumerConfig.GROUP_ID_CONFIG, "mailer",
ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest",
ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class,
ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class));
CountDownLatch allRead = new CountDownLatch(5);
// stands in for a shutdown hook: wakeup() is the one method safe from other threads
Thread stopper = new Thread(() -> {
try {
allRead.await();
} catch (InterruptedException e) {
return;
}
System.out.println("stopper thread calls wakeup()");
consumer.wakeup();
});
stopper.start();
try (consumer) {
consumer.subscribe(List.of("emails"));
while (true) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(1));
if (!records.isEmpty()) {
System.out.println("poll() returned " + records.count() + " records");
}
for (ConsumerRecord<String, String> r : records) {
System.out.println(" offset " + r.offset() + ": " + r.key() + " -> "
+ r.value());
allRead.countDown();
}
}
} catch (WakeupException e) {
System.out.println("poll() threw WakeupException; the loop ends and close() runs");
}
stopper.join();
Map<String, Object> defaults = ConsumerConfig.configDef().defaultValues();
System.out.println("consumer defaults in kafka-clients 4.2:");
for (String key : List.of("group.protocol", "enable.auto.commit",
"auto.commit.interval.ms", "auto.offset.reset", "max.poll.records",
"max.poll.interval.ms", "session.timeout.ms", "heartbeat.interval.ms",
"fetch.min.bytes", "fetch.max.wait.ms", "max.partition.fetch.bytes",
"isolation.level")) {
System.out.printf(" %-26s %s%n", key, defaults.get(key));
}
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 silenced.
// 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.ERROR);
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);
}
}
}
poll() returned 5 records
offset 0: user-1 -> welcome mail 1
offset 1: user-2 -> welcome mail 2
offset 2: user-3 -> welcome mail 3
offset 3: user-4 -> welcome mail 4
offset 4: user-5 -> welcome mail 5
stopper thread calls wakeup()
poll() threw WakeupException; the loop ends and close() runs
consumer defaults in kafka-clients 4.2:
group.protocol classic
enable.auto.commit true
auto.commit.interval.ms 5000
auto.offset.reset latest
max.poll.records 500
max.poll.interval.ms 300000
session.timeout.ms 45000
heartbeat.interval.ms 3000
fetch.min.bytes 1
fetch.max.wait.ms 500
max.partition.fetch.bytes 1048576
isolation.level read_uncommitted
- One
returned all five records, in offset order 0 to 4. The first poll also joined the group and received the partition assignment.poll() made the blockedwakeup() throwpoll() . The exception ended the loop, and try-with-resources calledWakeupException , which commits offsets and leaves the group at once, so the partitions move to other members without waiting for a timeout.close() : the default is still the classic rebalance protocol. The new protocol of KIP-848, generally available since Kafka 4.0, is enabled withgroup.protocol = classic ; see thegroup.protocol=consumerrebalancing page . withenable.auto.commit = true commits the position every 5 seconds duringauto.commit.interval.ms = 5000 . A crash loses up to 5 seconds of commits, so those records are read again: auto commit gives at-least-once delivery, not exactly-once.poll() means a new group starts at the end of each partition. That is why the example setsauto.offset.reset = latest .earliest andmax.poll.records = 500 together limit how long one batch may take: 500 records in at most 5 minutes. A later section breaks this rule on purpose.max.poll.interval.ms = 300000
The poll timeout, one second here, is only the longest time to wait when no data is available. A busy consumer's poll()
assign() and seek(): reading without a group
A tool that replays one partition from a chosen offset does not want a group or rebalancing. The program writes ten temperature readings alternately to two partitions, then reads partition 1 directly:
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 org.apache.kafka.clients.admin.NewTopic;
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 AssignAndSeek {
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
broker.addTopics(new NewTopic("readings", 2, (short) 1));
try (KafkaProducer<String, String> producer = new KafkaProducer<>(Map.of(
"bootstrap.servers", broker.getBrokersAsString(),
"key.serializer", StringSerializer.class,
"value.serializer", StringSerializer.class))) {
for (int i = 0; i < 10; i++) {
producer.send(new ProducerRecord<>("readings", i % 2, "sensor", "t=" + (20 + i)));
}
}
// no group.id: this consumer is not in a group and commits nothing
try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(Map.of(
"bootstrap.servers", broker.getBrokersAsString(),
"key.deserializer", StringDeserializer.class,
"value.deserializer", StringDeserializer.class))) {
TopicPartition p1 = new TopicPartition("readings", 1);
consumer.assign(List.of(p1));
System.out.println("assignment: " + consumer.assignment()
+ ", subscription: " + consumer.subscription());
System.out.println("end offset of " + p1 + ": " + consumer.endOffsets(List.of(p1)));
consumer.seek(p1, 2); // start at offset 2 of partition 1 only
System.out.println("from offset 2: " + readUpTo(consumer, 3));
consumer.seekToBeginning(List.of(p1));
System.out.println("position after seekToBeginning: " + consumer.position(p1));
System.out.println("from the start: " + readUpTo(consumer, 5));
try {
consumer.commitSync();
} catch (RuntimeException e) {
System.out.println("commitSync(): " + e.getClass().getSimpleName() + ": "
+ e.getMessage());
}
try {
consumer.subscribe(List.of("readings"));
} catch (RuntimeException e) {
System.out.println("subscribe(): " + e.getClass().getSimpleName());
}
}
broker.destroy();
}
static List<String> readUpTo(KafkaConsumer<String, String> consumer, int n) {
List<String> values = new ArrayList<>();
while (values.size() < n) {
for (ConsumerRecord<String, String> r : consumer.poll(Duration.ofSeconds(1))) {
if (values.size() < n) {
values.add(r.partition() + "/" + r.offset() + " " + r.value());
}
}
}
return values;
}
// 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 silenced.
// 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.ERROR);
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);
}
}
}
assignment: [readings-1], subscription: []
end offset of readings-1: {readings-1=5}
from offset 2: [1/2 t=25, 1/3 t=27, 1/4 t=29]
position after seekToBeginning: 0
from the start: [1/0 t=21, 1/1 t=23, 1/2 t=25, 1/3 t=27, 1/4 t=29]
commitSync(): InvalidGroupIdException: To use the group management or offset commit APIs, you must provide a valid group.id in the consumer configuration.
subscribe(): InvalidGroupIdException
- After
, the consumer owns partition 1 and has no subscription: the empty list shows that no group management is involved.assign() reported 5, the offset the next record will get. Partition 1 holds offsets 0 to 4.endOffsets started reading at offset 2, so the first three values were t=25, t=27 and t=29.seek(p1, 2) moved the position back to 0, and the five readings came again. Seeks are lazy: they take effect on the nextseekToBeginning orpoll() .position()- Without a
,group.id andcommitSync() both failed withsubscribe() . Since the 2.2 release the default group id is null, so a consumer without one cannot store its position in Kafka.InvalidGroupIdException
An assigned consumer with a group.idsubscribe()
How much one poll returns, and how fast
Two settings shape what poll()max.poll.recordsfetch.min.bytesfetch.min.bytes
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.ConsumerRecords;
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 PollTuning {
static String servers;
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
servers = broker.getBrokersAsString();
try {
broker.addTopics("logs", "alerts");
try (KafkaProducer<String, String> producer = producer()) {
for (int i = 0; i < 1200; i++) {
producer.send(new ProducerRecord<>("logs", "line " + i));
}
}
// 1. max.poll.records caps how many records one poll() hands over
for (int max : new int[] {500, 100}) {
try (KafkaConsumer<String, String> c = consumer(Map.of("max.poll.records", max))) {
c.assign(List.of(new TopicPartition("logs", 0)));
c.seekToBeginning(c.assignment());
List<Integer> sizes = new ArrayList<>();
int total = 0;
while (total < 1200) {
ConsumerRecords<String, String> batch = c.poll(Duration.ofSeconds(1));
if (!batch.isEmpty()) {
sizes.add(batch.count());
total += batch.count();
}
}
System.out.println("max.poll.records=" + max + ": poll sizes " + sizes);
}
}
// 2. fetch.min.bytes makes the broker hold a fetch until enough data exists
for (int minBytes : new int[] {1, 100000}) {
try (KafkaConsumer<String, String> c = consumer(Map.of(
"fetch.min.bytes", minBytes, "fetch.max.wait.ms", 500))) {
c.assign(List.of(new TopicPartition("alerts", 0)));
c.seekToEnd(c.assignment());
c.position(new TopicPartition("alerts", 0)); // resolve the end offset now
long best = Long.MAX_VALUE;
for (int round = 0; round < 3; round++) {
try (KafkaProducer<String, String> producer = producer()) {
long sent = System.nanoTime();
producer.send(new ProducerRecord<>("alerts", "disk full")).get();
while (c.poll(Duration.ofMillis(10)).isEmpty()) {
// wait for the record
}
best = Math.min(best, (System.nanoTime() - sent) / 1000000);
}
}
System.out.printf("fetch.min.bytes=%,d: one small record arrived after"
+ " %d ms (best of 3)%n", minBytes, best);
}
}
} finally {
broker.destroy();
}
}
static KafkaProducer<String, String> producer() {
return new KafkaProducer<>(Map.of("bootstrap.servers", servers,
"key.serializer", StringSerializer.class,
"value.serializer", StringSerializer.class));
}
static KafkaConsumer<String, String> consumer(Map<String, Object> settings) {
Map<String, Object> props = new HashMap<>(settings);
props.put("bootstrap.servers", servers);
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 silenced.
// 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.ERROR);
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);
}
}
}
max.poll.records=500: poll sizes [500, 500, 200]
max.poll.records=100: poll sizes [100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100]
fetch.min.bytes=1: one small record arrived after 31 ms (best of 3)
fetch.min.bytes=100,000: one small record arrived after 501 ms (best of 3)
- With the default cap of 500, the 1,200 records came in batches of 500, 500 and 200. With a cap of 100, they came in twelve batches of 100. The cap only splits what was fetched; the client still fetches in large requests and keeps the rest in its buffer.
- With
, the default, the broker answered as soon as the alert was written, and it reached the consumer within a few tens of milliseconds.fetch.min.bytes=1 - With
, the broker held the fetch, waiting for 100 KB that never came, untilfetch.min.bytes=100,000 ran out after 500 ms. Every lone record paid that half-second.fetch.max.wait.ms
Raising fetch.min.bytesmax.partition.fetch.bytesfetch.max.bytes
One consumer, one thread
A common mistake is to commit from a worker thread while the polling thread is still inside poll()
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.concurrent.CompletableFuture;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
public class ThreadSafety {
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
try {
broker.addTopics("tasks");
try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(Map.of(
"bootstrap.servers", broker.getBrokersAsString(),
"group.id", "workers",
"key.deserializer", StringDeserializer.class,
"value.deserializer", StringDeserializer.class))) {
consumer.subscribe(List.of("tasks"));
// the main thread is inside a 3-second poll() while another thread calls in
CompletableFuture<String> other = CompletableFuture.supplyAsync(() -> {
sleep(500);
try {
consumer.commitSync();
return "commitSync() from another thread worked";
} catch (RuntimeException e) {
// the message goes on with thread ids, which vary from run to run
String message = e.getMessage();
return "other thread: " + e.getClass().getSimpleName() + ": "
+ message.substring(0, message.indexOf('.') + 1);
}
});
consumer.poll(Duration.ofSeconds(3));
System.out.println(other.get());
}
} finally {
broker.destroy();
}
}
static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
// 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 silenced.
// 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.ERROR);
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);
}
}
}
other thread: ConcurrentModificationException: KafkaConsumer is not safe for multi-threaded access.
- The worker thread's
failed at once withcommitSync() , because the main thread was insideConcurrentModificationException . The full message also names both threads.poll() - The check is a lock taken by every public method except
, so the error appears whenever two threads overlap, and only then. Code that works in a test can fail under load.wakeup()
Three patterns avoid the problem. Run several consumers, each on its own thread, in one group; the partition count limits how many do useful work. Or let one thread poll and hand records to a pool, and pass the offsets of finished records back to the polling thread, which commits them. Or use a framework that does the bookkeeping: Spring's listener containers, or the Confluent Parallel Consumer for per-key parallelism.
Slow processing and max.poll.interval.ms
Image resizing is slow work, here 300 ms per record. The consumer is allowed at most 2 seconds between polls (max.poll.interval.ms=2000
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.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.KafkaException;
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 SlowProcessing {
static String servers;
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
servers = broker.getBrokersAsString();
try {
broker.addTopics("images");
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 < 20; i++) {
producer.send(new ProducerRecord<>("images", "img-" + i));
}
}
// each image takes 300 ms; a poll may not be more than 2 s after the last one
run("max.poll.records=10", 10);
run("max.poll.records=3 ", 3);
} finally {
broker.destroy();
}
}
static void run(String label, int maxRecords) {
Map<String, Object> props = new HashMap<>();
props.put("bootstrap.servers", servers);
props.put("group.id", "resizer-" + maxRecords);
props.put("auto.offset.reset", "earliest");
props.put("enable.auto.commit", false);
props.put("max.poll.interval.ms", 2000);
props.put("max.poll.records", maxRecords);
props.put("key.deserializer", StringDeserializer.class);
props.put("value.deserializer", StringDeserializer.class);
try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props)) {
consumer.subscribe(List.of("images"));
int done = 0;
while (done < 20) {
ConsumerRecords<String, String> batch = consumer.poll(Duration.ofSeconds(1));
if (batch.isEmpty()) {
continue;
}
long start = System.nanoTime();
batch.forEach(r -> sleep(300)); // the "work"
long ms = (System.nanoTime() - start) / 1000000;
try {
consumer.commitSync();
done += batch.count();
System.out.printf("%s: %2d records in %.1f s, committed (%d done)%n",
label, batch.count(), ms / 1000.0, done);
} catch (KafkaException e) {
System.out.printf("%s: %2d records in %.1f s, commit failed: %s%n",
label, batch.count(), ms / 1000.0, e.getClass().getSimpleName());
System.out.println(" " + e.getMessage());
return;
}
}
}
}
static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
// 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 silenced.
// 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.ERROR);
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);
}
}
}
max.poll.records=10: 10 records in 3.0 s, commit failed: CommitFailedException
Offset commit cannot be completed since the consumer is not part of an active group for auto partition assignment; it is likely that the consumer was kicked out of the group.
max.poll.records=3 : 3 records in 0.9 s, committed (3 done)
max.poll.records=3 : 3 records in 0.9 s, committed (6 done)
max.poll.records=3 : 3 records in 0.9 s, committed (9 done)
max.poll.records=3 : 3 records in 0.9 s, committed (12 done)
max.poll.records=3 : 3 records in 0.9 s, committed (15 done)
max.poll.records=3 : 3 records in 0.9 s, committed (18 done)
max.poll.records=3 : 2 records in 0.6 s, committed (20 done)
- Ten records took about 3 seconds, longer than the 2-second limit. The client's heartbeat thread noticed that
had not been called in time and left the group, so the coordinator gave the partition away.poll() - The commit after the batch then failed with
: "the consumer was kicked out of the group". All ten images were processed, but their offsets were not committed, so another member, or this one after rejoining, processes them again.CommitFailedException - With 3 records per poll, each batch took 0.9 seconds, well inside the limit, and all 20 records were committed in seven batches, the last one with 2 records.
Heartbeats run on a background thread, so a slow loop does not miss them. Two separate timeouts apply. session.timeout.msmax.poll.interval.msmax.poll.recordspause()poll()resume()
Choosing consumer settings
| Situation | Approach |
|---|---|
| A service that scales out | subscribe()group.id |
| Replay or inspect one partition | assign()seek() |
| A new group must read existing data | auto.offset.reset=earliest |
| No record may be skipped after a crash | enable.auto.commit=false |
| Slow work per record | Smaller max.poll.recordspause() |
| High throughput on busy topics | Larger fetch.min.bytesfetch.max.wait.ms |
| Low latency on quiet topics | Default fetch.min.bytes=1 |
| Fewer pauses when members come and go | group.protocol=consumer |
| Clean shutdown | wakeup()close() |
Related pages: