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.

Share

Contents

How a Kafka consumer reads

A Kafka consumer pulls records from brokers. The broker never pushes anything: the application calls poll() in a loop, and each call returns the records that have arrived since the last one. The consumer remembers a position per partition, the offset of the next record to read, and moves it forward as it hands records over.

Behind poll() the client does several jobs:

  • Group membership: a consumer with a group.id 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).
  • Fetching: the client sends fetch requests to the leader of each assigned partition and keeps the answers in a buffer, so that most poll() calls return data already in memory.
  • Liveness: heartbeats tell the coordinator the member is alive, and the time between poll() calls tells it the member is still making progress.
  • Offset commits: by default, the position is committed to the group every 5 seconds, from inside poll(), and on close().

A KafkaConsumer is not thread-safe, unlike the producer: one thread owns it, and only wakeup() may be called from elsewhere. To process in parallel, run one consumer per thread in the same group, or hand records from one polling thread to workers.

Two ways to get partitions
MethodPartitions chosen byCommitsBest for
subscribe(topics)The group coordinator, with rebalancingTo the groupServices that scale out and survive failures
assign(partitions)The applicationOptional; needs a group.idTools, replays, tests and stream processors that manage their own state

The examples use kafka-clients 4.2.2. Each program starts its own single-node Kafka 4.2 broker inside the JVM first, with EmbeddedKafkaKraftBroker from spring-kafka-test (the startBroker method at the end). The consumer code is the same against a real cluster, which has three or more brokers.

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(), called from a shutdown hook; here a second thread calls it once all five records have been read. The program also prints the consumer defaults, read from the client library:

Java
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);
        }
    }
}
Output
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 poll() returned all five records, in offset order 0 to 4. The first poll also joined the group and received the partition assignment.
  • wakeup() made the blocked poll() throw WakeupException. The exception ended the loop, and try-with-resources called close(), which commits offsets and leaves the group at once, so the partitions move to other members without waiting for a timeout.
  • group.protocol = classic: the default is still the classic rebalance protocol. The new protocol of KIP-848, generally available since Kafka 4.0, is enabled with group.protocol=consumer; see the rebalancing page.
  • enable.auto.commit = true with auto.commit.interval.ms = 5000 commits the position every 5 seconds during poll(). 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.
  • auto.offset.reset = latest means a new group starts at the end of each partition. That is why the example sets earliest.
  • max.poll.records = 500 and max.poll.interval.ms = 300000 together limit how long one batch may take: 500 records in at most 5 minutes. A later section breaks this rule on purpose.

The poll timeout, one second here, is only the longest time to wait when no data is available. A busy consumer's poll() returns as soon as it has records.

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:

Java
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);
        }
    }
}
Output
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 assign(), the consumer owns partition 1 and has no subscription: the empty list shows that no group management is involved.
  • endOffsets reported 5, the offset the next record will get. Partition 1 holds offsets 0 to 4.
  • seek(p1, 2) started reading at offset 2, so the first three values were t=25, t=27 and t=29.
  • seekToBeginning moved the position back to 0, and the five readings came again. Seeks are lazy: they take effect on the next poll() or position().
  • Without a group.id, commitSync() and subscribe() both failed with InvalidGroupIdException. Since the 2.2 release the default group id is null, so a consumer without one cannot store its position in Kafka.

An assigned consumer with a group.id can commit offsets, but its partitions are never rebalanced. If it dies, nobody takes over its partitions until the application starts another. Seeking also works with subscribe(), but only for partitions currently assigned, so it is usually done in a rebalance listener; the offsets page shows seeking by timestamp and resetting group offsets.

How much one poll returns, and how fast

Two settings shape what poll() delivers: max.poll.records caps the batch handed to the application, and fetch.min.bytes tells the broker how much data to collect before answering a fetch. The program reads 1,200 log lines with two batch caps, then measures how long a single small alert takes to arrive with two values of fetch.min.bytes:

Java
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);
        }
    }
}
Output
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 fetch.min.bytes=1, the default, the broker answered as soon as the alert was written, and it reached the consumer within a few tens of milliseconds.
  • With fetch.min.bytes=100,000, the broker held the fetch, waiting for 100 KB that never came, until fetch.max.wait.ms ran out after 500 ms. Every lone record paid that half-second.

Raising fetch.min.bytes cuts the number of fetch requests on busy topics, at the price of latency on quiet ones. max.partition.fetch.bytes (1 MB) and fetch.max.bytes (50 MB) cap how much one fetch can bring back, per partition and in total. These are timings from a broker in the same JVM, best of 3 runs; over a network each round trip adds its own latency.

One consumer, one thread

A common mistake is to commit from a worker thread while the polling thread is still inside poll(). The consumer checks for this on every call:

Java
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);
        }
    }
}
Output
other thread: ConcurrentModificationException: KafkaConsumer is not safe for multi-threaded access.
  • The worker thread's commitSync() failed at once with ConcurrentModificationException, because the main thread was inside poll(). The full message also names both threads.
  • The check is a lock taken by every public method except wakeup(), so the error appears whenever two threads overlap, and only then. Code that works in a test can fail under load.

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, lowered from 5 minutes to keep the run short). The program first fetches 10 records per poll, then 3:

Java
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);
        }
    }
}
Output
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 poll() had not been called in time and left the group, so the coordinator gave the partition away.
  • The commit after the batch then failed with CommitFailedException: "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.
  • 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.ms, 45 seconds by default, detects a dead process or a lost network. max.poll.interval.ms detects a live process that has stopped polling, and it is the one slow processing breaks. Keep a batch's worst-case processing time well under it, by lowering max.poll.records or raising the interval. For work that can take minutes, pause() the partitions, process on another thread, keep calling poll() (which then returns nothing for paused partitions), and resume() when done.

Choosing consumer settings

Situations and the approach that fits
SituationApproach
A service that scales outsubscribe() with a group.id, one consumer per thread
Replay or inspect one partitionassign() plus seek(), no group
A new group must read existing dataauto.offset.reset=earliest
No record may be skipped after a crashenable.auto.commit=false and commit after processing (see offsets)
Slow work per recordSmaller max.poll.records, or pause() with a worker thread
High throughput on busy topicsLarger fetch.min.bytes with a bounded fetch.max.wait.ms
Low latency on quiet topicsDefault fetch.min.bytes=1
Fewer pauses when members come and gogroup.protocol=consumer (see rebalancing)
Clean shutdownwakeup() from a shutdown hook, then close()

Related pages: Kafka producers, offsets and commits, configuration and dead letter topics for records that cannot be processed. Spring applications usually consume with @KafkaListener, which runs this poll loop for you.