Kafka performance tuning

Kafka is fast by design, but its defaults favour latency and safety over raw throughput, and a few settings change throughput several times over. This page explains where the time goes in a producer and a consumer, then measures batching, compression, fetch sizes and partition parallelism against a broker running inside each program.

Share

Contents

Where the time goes

A Kafka producer does not send records one by one. send() serializes the record, picks a partition and appends it to an in-memory batch for that partition. A background thread sends a batch when it is full (batch.size, 16 KB by default) or has waited linger.ms (5 ms by default since Kafka 4.0), and up to 5 requests per broker can be in flight at once. The broker appends each batch to the log as it arrived, without unpacking it, and consumers later fetch whole batches again.

Almost every throughput setting is therefore about the size of the units that move: bigger batches mean fewer requests, fewer network round trips and less work per record on every side. Compression works on whole batches too, so bigger batches also compress better. The cost is latency: a record may wait for its batch to fill. On the consumer side, the same logic applies to fetch sizes, and parallelism is bounded by the number of partitions, because each partition is read by one consumer of a group at a time.

The settings with the largest effect on throughput
SettingDefault (Kafka 4.2)Raise it forCost
batch.size16384High-volume producersMemory per partition, up to buffer.memory
linger.ms5Producers that send in bursts or at low ratesUp to that much extra latency per record
compression.typenoneText, JSON, repetitive dataCPU on the producer, and on consumers
max.poll.records500Fast per-record processingLonger time between polls
max.partition.fetch.bytes1048576Consumers that fall behindConsumer memory
fetch.min.bytes1Many consumers on a busy clusterUp to fetch.max.wait.ms (500) latency
Partition countSet per topicMore parallel consumersMore files, leaders and memory on brokers

Each program starts its own single-node KRaft broker in the JVM with EmbeddedKafkaKraftBroker from spring-kafka-test; a real cluster has 3 or more brokers, and its network adds latency that makes batching matter even more. The timings are rough comparisons on a shared 2-core Linux container that other jobs were using at the same time, with client and broker in one JVM. Each is the best of 3 runs after a warm-up run, and only ratios to the first row are printed, because absolute numbers say nothing about your hardware. Ratios also moved between runs of the same program by up to about a factor of two, so read them as directions, not results. Counts such as bytes, requests and polls do not depend on the machine.

Producer batching

The program sends 20,000 records of 200 bytes to a three-partition topic as fast as it can, five times with different linger.ms and batch.size, and reads the producer's own metrics for records per request and average batch size:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
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 ProducerBatching {

    static final int RECORDS = 20000;
    static final String VALUE = "x".repeat(200);

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        String bootstrap = broker.getBrokersAsString();
        try (Admin admin = Admin.create(Map.<String, Object>of("bootstrap.servers", bootstrap))) {
            admin.createTopics(List.of(new NewTopic("load", 3, (short) 1))).all().get();
        }
        List<Map<String, String>> variants = List.of(
                Map.of("linger.ms", "0", "batch.size", "16384"),
                Map.of("linger.ms", "5", "batch.size", "16384"),
                Map.of("linger.ms", "20", "batch.size", "16384"),
                Map.of("linger.ms", "20", "batch.size", "131072"),
                Map.of("linger.ms", "5", "batch.size", "1024"));
        run(bootstrap, variants.get(0)); // warms up the JIT compiler in client and broker
        double baseline = 0;
        System.out.printf("%-34s %9s %13s %10s%n", "settings", "time", "records/req",
                "batch avg");
        for (Map<String, String> v : variants) {
            double[] result = run(bootstrap, v);
            if (baseline == 0) {
                baseline = result[0];
            }
            System.out.printf("%-34s %8.2fx %13.0f %9.0fB%n",
                    "linger.ms=" + v.get("linger.ms") + " batch.size=" + v.get("batch.size"),
                    result[0] / baseline, result[1], result[2]);
        }
        broker.destroy();
    }

    // best of 3 runs: elapsed nanos, records per produce request, average batch bytes
    static double[] run(String bootstrap, Map<String, String> settings) throws Exception {
        double best = Double.MAX_VALUE;
        double perRequest = 0;
        double batch = 0;
        for (int round = 0; round < 3; round++) {
            Map<String, Object> props = new HashMap<>(settings);
            props.put("bootstrap.servers", bootstrap);
            try (KafkaProducer<String, String> producer = new KafkaProducer<>(props,
                    new StringSerializer(), new StringSerializer())) {
                producer.send(new ProducerRecord<>("load", "warm-up")).get();
                long start = System.nanoTime();
                List<Future<RecordMetadata>> futures = new ArrayList<>(RECORDS);
                for (int i = 0; i < RECORDS; i++) {
                    futures.add(producer.send(new ProducerRecord<>("load", "k" + i, VALUE)));
                }
                for (Future<RecordMetadata> f : futures) {
                    f.get();
                }
                best = Math.min(best, System.nanoTime() - start);
                perRequest = metric(producer, "records-per-request-avg");
                batch = metric(producer, "batch-size-avg");
            }
        }
        return new double[] {best, perRequest, batch};
    }

    static double metric(KafkaProducer<String, String> producer, String name) {
        return (Double) producer.metrics().entrySet().stream()
                .filter(e -> e.getKey().group().equals("producer-metrics")
                        && e.getKey().name().equals(name))
                .findFirst().orElseThrow().getValue().metricValue();
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // 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
settings                                time   records/req  batch avg
linger.ms=0 batch.size=16384           1.00x           220     16076B
linger.ms=5 batch.size=16384           0.85x           220     16076B
linger.ms=20 batch.size=16384          0.73x           220     16076B
linger.ms=20 batch.size=131072         0.29x          1539    116456B
linger.ms=5 batch.size=1024            5.67x            12       918B
  • With the default batch.size of 16 KB, every request carried about 220 records, whatever linger.ms was. The producer had more records waiting than fit into a batch, so batches filled up before the linger time ran out. A longer linger.ms still helped a little, by a margin that varied from run to run.
  • A batch.size of 128 KB put about 1,540 records into each request, seven times as many, and the run took a fraction of the time of the first row: the clearest win on this page.
  • A 1 KB batch.size left room for only about 12 records per request, and the same work took several times as long as with the default. Batches that are too small multiply the number of requests, and every request has a fixed cost on the client and the broker.

With a steady, low rate of records the picture changes: batches then never fill, and linger.ms decides how many records share a request. The Kafka 4.0 change of the default from 0 to 5 ms (KIP-1030) was made for that case. A program that waits for each send to finish before the next one defeats batching altogether; Spring Kafka's KafkaTemplate page measures that pattern.

Compression codecs

Kafka supports four codecs, each a different trade between size and CPU. The program sends the same 20,000 JSON orders, built with a fixed random seed, once per codec into its own topic, and reads the size of the partition on disk from describeLogDirs:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.Future;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.TopicPartition;
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 CompressionCodecs {

    static final int RECORDS = 20000;

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        String bootstrap = broker.getBrokersAsString();
        List<String> values = orders();
        long raw = values.stream().mapToLong(String::length).sum();
        System.out.println(RECORDS + " JSON orders, " + raw / 1024 + " KB of values");
        System.out.printf("%-8s %12s %10s %8s%n", "codec", "bytes on disk", "vs none", "time");
        List<String> codecs = List.of("none", "gzip", "snappy", "lz4", "zstd");
        send(bootstrap, "warm-up", "none", values); // warms up the JIT compiler
        long noneBytes = 0;
        double noneTime = 0;
        try (Admin admin = Admin.create(Map.<String, Object>of("bootstrap.servers", bootstrap))) {
            for (String codec : codecs) {
                double best = Double.MAX_VALUE;
                for (int round = 0; round < 3; round++) {
                    String topic = codec + "-" + round;
                    admin.createTopics(List.of(new NewTopic(topic, 1, (short) 1))).all().get();
                    best = Math.min(best, send(bootstrap, topic, codec, values));
                }
                long bytes = admin.describeLogDirs(List.of(0)).allDescriptions().get().get(0)
                        .values().iterator().next().replicaInfos()
                        .get(new TopicPartition(codec + "-0", 0)).size();
                if (codec.equals("none")) {
                    noneBytes = bytes;
                    noneTime = best;
                }
                System.out.printf("%-8s %12d %9.0f%% %7.2fx%n", codec, bytes,
                        100.0 * bytes / noneBytes, best / noneTime);
            }
        } finally {
            broker.destroy();
        }
    }

    // sends every value and returns the elapsed nanoseconds
    static double send(String bootstrap, String topic, String codec, List<String> values)
            throws Exception {
        try (KafkaProducer<String, String> producer = new KafkaProducer<>(Map.of(
                "bootstrap.servers", bootstrap, "compression.type", codec,
                "linger.ms", "10", "batch.size", "65536"),
                new StringSerializer(), new StringSerializer())) {
            long start = System.nanoTime();
            List<Future<RecordMetadata>> futures = new ArrayList<>(values.size());
            for (String v : values) {
                futures.add(producer.send(new ProducerRecord<>(topic, v)));
            }
            for (Future<RecordMetadata> f : futures) {
                f.get();
            }
            return System.nanoTime() - start;
        }
    }

    // realistic, repetitive JSON: field names repeat, values vary, fixed seed
    static List<String> orders() {
        Random random = new Random(42);
        String[] items = {"apple", "pear", "plum", "fig", "kiwi", "mango"};
        String[] cities = {"Berlin", "Lisbon", "Oslo", "Madrid", "Vienna"};
        List<String> out = new ArrayList<>(RECORDS);
        for (int i = 0; i < RECORDS; i++) {
            out.add("{\"orderId\":" + (100000 + i) + ",\"customerId\":\"c-"
                    + random.nextInt(5000) + "\",\"item\":\"" + items[random.nextInt(6)]
                    + "\",\"quantity\":" + (1 + random.nextInt(9)) + ",\"price\":"
                    + random.nextInt(10000) / 100.0 + ",\"city\":\""
                    + cities[random.nextInt(5)] + "\",\"status\":\"CREATED\"}");
        }
        return out;
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // 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
20000 JSON orders, 2252 KB of values
codec    bytes on disk    vs none     time
none          2506939       100%    1.00x
gzip           352966        14%    1.53x
snappy         625046        25%    1.00x
lz4            634002        25%    0.87x
zstd           389496        16%    0.83x
  • Without compression, the partition took a little more than the raw values, because each record and batch carries headers.
  • gzip made it the smallest, about a seventh of the original, but it was the slowest codec to produce with: it costs the most CPU.
  • zstd came close to gzip's size, at a time close to sending uncompressed data: its CPU cost is roughly paid back by having far fewer bytes to write and copy.
  • snappy and lz4 compressed to about a quarter of the size with the least CPU, and took about as long as sending uncompressed data, or less. On most clusters, lz4 or zstd is the best default for text data.

Compression is done by the producer, per batch, and the broker stores the compressed batch as it is, unless the topic's own compression.type asks for a different codec, which makes the broker recompress every batch. Leave the topic at its default, producer. Consumers decompress, so they pay the CPU too. The ratios depend heavily on the data: JSON with repeated field names compresses well, while already compressed images or encrypted payloads do not shrink at all and only cost CPU.

Consumer fetch sizes

A consumer fetches batches from each partition and then hands them out through poll(). The program reads 100,000 records of about 100 bytes from one partition with four settings, counting the fetch requests sent and the poll() calls made:

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 java.util.TreeMap;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.NewTopic;
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 ConsumerFetching {

    static final int RECORDS = 100000;

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        String bootstrap = broker.getBrokersAsString();
        try (Admin admin = Admin.create(Map.<String, Object>of("bootstrap.servers", bootstrap))) {
            admin.createTopics(List.of(new NewTopic("events", 1, (short) 1))).all().get();
        }
        try (KafkaProducer<String, String> producer = new KafkaProducer<>(Map.of(
                "bootstrap.servers", bootstrap, "batch.size", "65536", "linger.ms", "10"),
                new StringSerializer(), new StringSerializer())) {
            for (int i = 0; i < RECORDS; i++) {
                producer.send(new ProducerRecord<>("events", "event-" + i + "-" + "y".repeat(90)));
            }
        }
        List<Map<String, String>> variants = List.of(
                Map.of(),
                Map.of("max.poll.records", "10"),
                Map.of("max.partition.fetch.bytes", "16384"),
                Map.of("max.poll.records", "2000", "max.partition.fetch.bytes", "4194304"));
        read(bootstrap, variants.get(0)); // warms up the JIT compiler
        double baseline = 0;
        System.out.printf("%-60s %6s %8s %7s%n", "settings (defaults otherwise)", "time",
                "fetches", "polls");
        for (Map<String, String> v : variants) {
            double best = Double.MAX_VALUE;
            long[] counts = null;
            for (int round = 0; round < 3; round++) {
                long start = System.nanoTime();
                counts = read(bootstrap, v);
                best = Math.min(best, System.nanoTime() - start);
            }
            if (baseline == 0) {
                baseline = best;
            }
            String label = v.isEmpty() ? "defaults" : new TreeMap<>(v).toString();
            System.out.printf("%-60s %5.2fx %8d %7d%n", label, best / baseline, counts[0],
                    counts[1]);
        }
        broker.destroy();
    }

    // reads the whole partition; returns fetch requests sent and poll() calls made
    static long[] read(String bootstrap, Map<String, String> settings) {
        Map<String, Object> props = new HashMap<>(settings);
        props.put("bootstrap.servers", bootstrap);
        TopicPartition tp = new TopicPartition("events", 0);
        try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props,
                new StringDeserializer(), new StringDeserializer())) {
            consumer.assign(List.of(tp));
            consumer.seekToBeginning(List.of(tp));
            long seen = 0;
            long polls = 0;
            while (seen < RECORDS) {
                seen += consumer.poll(Duration.ofMillis(500)).count();
                polls++;
            }
            double fetches = (Double) consumer.metrics().entrySet().stream()
                    .filter(e -> e.getKey().name().equals("fetch-total")
                            && e.getKey().group().equals("consumer-fetch-manager-metrics"))
                    .findFirst().orElseThrow().getValue().metricValue();
            return new long[] {(long) fetches, polls};
        }
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // 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
settings (defaults otherwise)                                  time  fetches   polls
defaults                                                      1.00x       11     203
{max.poll.records=10}                                         1.09x       11   10001
{max.partition.fetch.bytes=16384}                             1.19x      171     341
{max.partition.fetch.bytes=4194304, max.poll.records=2000}    0.91x        3      51
  • With the defaults, the consumer needed only 11 fetch requests for the 100,000 records, because each fetch returns up to 1 MB per partition (max.partition.fetch.bytes). poll() then handed them out in about 200 calls of up to 500 records.
  • max.poll.records=10 sent the same 11 fetches, but needed 10,001 calls to poll(). The records were already in memory, so the extra calls cost less than one might expect.
  • A 16 KB max.partition.fetch.bytes raised the fetches to 171, each a round trip to the broker, and the read became slower.
  • 4 MB fetches and 2,000 records per poll needed only 3 fetches and 51 polls, and were the fastest. The gain over the defaults is modest here because the broker is in the same JVM; across a network each saved round trip counts more.

max.poll.records does not change fetching; it only limits how many already fetched records one poll() returns. Lower it when processing a record is slow, so that the time between polls stays under max.poll.interval.ms. fetch.min.bytes and fetch.max.wait.ms make the broker hold a fetch until enough data is there, which reduces requests from consumers that are caught up at the cost of some latency.

Partitions and parallel consumers

When processing a record takes real time, for example a database write, throughput comes from processing several partitions at once. Each record here takes 5 ms; the program runs groups of 1, 2, 3, 6 and 8 consumers on a topic with 6 partitions, waits until every member has its partitions, and then sends 600 records spread evenly:

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 java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.ConsumerGroupDescription;
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.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 PartitionParallelism {

    static final int RECORDS = 600;

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        String bootstrap = broker.getBrokersAsString();
        double baseline = 0;
        System.out.printf("%-10s %6s  %s%n", "consumers", "time", "records per consumer");
        try (Admin admin = Admin.create(Map.<String, Object>of("bootstrap.servers", bootstrap))) {
            for (int consumers : List.of(1, 2, 3, 6, 8)) {
                Object[] result = run(admin, bootstrap, consumers);
                double time = (Double) result[0];
                if (baseline == 0) {
                    baseline = time;
                }
                System.out.printf("%-10d %5.2fx  %s%n", consumers, time / baseline, result[1]);
            }
        } finally {
            broker.destroy();
        }
    }

    // A group of consumers on a 6-partition topic; each record takes 5 ms to process.
    // Returns the time from the first send to the last processed record, and the
    // number of records each consumer processed.
    static Object[] run(Admin admin, String bootstrap, int consumers) throws Exception {
        String topic = "jobs-" + consumers;
        admin.createTopics(List.of(new NewTopic(topic, 6, (short) 1))).all().get();
        AtomicInteger done = new AtomicInteger();
        Map<Integer, Integer> perConsumer = new ConcurrentHashMap<>();
        List<Thread> threads = new ArrayList<>();
        for (int c = 0; c < consumers; c++) {
            int id = c;
            perConsumer.put(id, 0);
            threads.add(Thread.ofPlatform().start(() -> {
                try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(Map.of(
                        "bootstrap.servers", bootstrap, "group.id", topic,
                        "group.protocol", "consumer", "auto.offset.reset", "earliest"),
                        new StringDeserializer(), new StringDeserializer())) {
                    consumer.subscribe(List.of(topic));
                    while (done.get() < RECORDS) {
                        for (ConsumerRecord<String, String> r : consumer.poll(
                                Duration.ofMillis(100))) {
                            sleep(5); // the work for one record
                            perConsumer.merge(id, 1, Integer::sum);
                            done.incrementAndGet();
                        }
                    }
                }
            }));
        }
        // wait until every consumer has joined and all 6 partitions are assigned
        while (!ready(admin, topic, consumers)) {
            Thread.sleep(100);
        }
        long start = System.nanoTime();
        try (KafkaProducer<String, String> producer = new KafkaProducer<>(
                Map.of("bootstrap.servers", bootstrap),
                new StringSerializer(), new StringSerializer())) {
            for (int i = 0; i < RECORDS; i++) {
                producer.send(new ProducerRecord<>(topic, i % 6, null, "job-" + i));
            }
        }
        for (Thread t : threads) {
            t.join();
        }
        List<Integer> counts = new ArrayList<>(perConsumer.values());
        counts.sort(null);
        return new Object[] {(double) (System.nanoTime() - start), counts};
    }

    static boolean ready(Admin admin, String group, int consumers) throws Exception {
        try {
            ConsumerGroupDescription d = admin.describeConsumerGroups(List.of(group)).all()
                    .get().get(group);
            int assigned = d.members().stream()
                    .mapToInt(m -> m.assignment().topicPartitions().size()).sum();
            return d.members().size() == consumers && assigned == 6;
        } catch (ExecutionException e) {
            return false; // the group does not exist until the first member joins
        }
    }

    static void sleep(long ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // 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
consumers    time  records per consumer
1           1.00x  [600]
2           0.64x  [300, 300]
3           0.48x  [200, 200, 200]
6           0.31x  [100, 100, 100, 100, 100, 100]
8           0.35x  [0, 0, 100, 100, 100, 100, 100, 100]
  • One consumer processed all 600 records, which takes at least 3 seconds at 5 ms each.
  • Two, three and six consumers split the partitions evenly, 300, 200 and 100 records each, and the time fell with each step, although less than in proportion, because the 2-core machine also ran the broker and the producer.
  • With 8 consumers, two got no partition and processed nothing, and the time was no better than with 6. A group can use at most as many consumers as the topic has partitions; the rest stand by, which is only useful as spare capacity for a failure.

Choose the partition count for the parallelism you will need, because adding partitions later moves keys to other partitions, as Kafka cluster administration shows. More partitions are not free either: each one is a set of files and a leader on the brokers, and each adds to end-to-end latency when producers spread records thinly. When processing is slow but the partition count cannot grow, process records from one partition on several threads, keeping the order per key, as libraries such as Confluent's parallel consumer do; that was not run here.

Measuring your own cluster

Results from a laptop or a container do not predict a production cluster, so measure on the real thing. Kafka ships two load generators, run here only as commands from the documentation, since their output is absolute numbers for one machine:

Shell
bin/kafka-producer-perf-test.sh --topic perf --num-records 1000000 --record-size 200 \
  --throughput -1 --producer-props bootstrap.servers=kafka-1:9092 acks=all \
  linger.ms=20 batch.size=131072 compression.type=lz4
bin/kafka-consumer-perf-test.sh --bootstrap-server kafka-1:9092 --topic perf \
  --messages 1000000
  • Change one setting at a time, and repeat each run, since cloud networks and disks vary from minute to minute.
  • Watch the brokers too: request handler idle percentage, network processor idle percentage and disk use show which resource limits throughput; see Kafka monitoring.
  • Test with real data: compression ratios and batch fill depend on record sizes and keys.
  • Replication costs: with acks=all, each batch waits for the in-sync followers. One in-process broker has no followers, so this page could not measure that cost; on a real cluster, compare acks=1 and acks=all with the perf tool, and keep acks=all wherever losing records matters.

Choosing settings

Goals and settings that fit
GoalSettings
Maximum producer throughputbatch.size 64 to 256 KB, linger.ms 10 to 50, compression.type=lz4 or zstd
Lowest latency per recordDefaults, or linger.ms=0; no compression for tiny records
Smallest storage and network usezstd, with large batches
Cheap CPU and good sizelz4 or snappy
Consumers that fall behind on large backlogsLarger max.partition.fetch.bytes and max.poll.records
Slow processing per recordMore partitions and consumers, smaller max.poll.records
Many idle consumersHigher fetch.min.bytes

The producer settings are explained in depth on the Kafka producer, the consumer side on the Kafka consumer, and choosing partition counts on Kafka topics and partitions. Whether the tuning worked shows in consumer lag.