Kafka configuration: what goes where

Kafka settings live in clients, topics, brokers and groups, and each level is set and changed differently. This page explains how Kafka resolves a value, then runs the details that catch people out: typos that only log at INFO, secrets from config providers, runtime topic changes and the settings that decide durability.

Share

Contents

Where Kafka settings live

Kafka has several hundred configuration settings, but they belong to a few distinct places, and most confusion comes from setting a value in the wrong one. A producer's linger.ms means nothing to a broker, and a topic's retention.ms means nothing to a client.

The levels of Kafka configuration
LevelSet whereChanged howExamples
ClientThe Properties or Map passed to a producer, consumer or admin clientRestart the clientacks, linger.ms, group.id, max.poll.records
TopicTopic creation, or incrementalAlterConfigs laterAt runtimeretention.ms, cleanup.policy, min.insync.replicas
Broker, dynamicThe Admin API, for one broker or for allAt runtime, stored in the cluster metadatalog.retention.ms, num.io.threads, listener certificates
Broker, staticserver.propertiesRestart the brokerlog.dirs, process.roles, node.id
GroupThe Admin API, per consumer or share groupAt runtimeshare.auto.offset.reset, consumer.session.timeout.ms

Many topic settings have a broker-side default with a different name: the topic's retention.ms falls back to the broker's log.retention.ms, and max.message.bytes to message.max.bytes. For a topic, Kafka uses the first value it finds in this order: the topic's own override, a dynamic setting for that broker, a dynamic default for all brokers, server.properties, and finally the built-in default.

On the client side, every setting is declared in a ConfigDef with a type, a default, a validator and an importance. ProducerConfig, ConsumerConfig and AdminClientConfig each hold one, together with constants such as ProducerConfig.LINGER_MS_CONFIG for the names. The examples use kafka-clients 4.2.2; those that need a broker start a Kafka 4.2 cluster inside the JVM first, with EmbeddedKafkaKraftBroker from spring-kafka-test. A real cluster has three or more brokers.

How client settings are parsed and checked

A client checks its settings once, in its constructor. Values chosen to break the rules show what it accepts and what it rejects, and a misspelt name shows what it does not catch:

Java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import java.util.HashMap;
import java.util.Map;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.config.ConfigDef;
import org.apache.kafka.common.config.ConfigException;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ConfigParsing {

    public static void main(String[] args) {
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ch.qos.logback.classic.Logger root =
                (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
        root.setLevel(Level.INFO);
        root.detachAndStopAllAppenders();       // keep the console quiet ...
        ListAppender<ILoggingEvent> log = new ListAppender<>();
        log.start();
        root.addAppender(log);                  // ... and collect log events in a list

        ConfigDef.ConfigKey linger = ProducerConfig.configDef().configKeys().get("linger.ms");
        System.out.println("linger.ms: type " + linger.type + ", default " + linger.defaultValue
                + ", importance " + linger.importance);
        ConfigDef.ConfigKey acks = ProducerConfig.configDef().configKeys().get("acks");
        System.out.println("acks: type " + acks.type + ", valid values " + acks.validator);

        parse("linger.ms as the string \"20\"", Map.of("linger.ms", "20"));
        parse("linger.ms as the int 20", Map.of("linger.ms", 20));
        parse("linger.ms = \"20ms\"", Map.of("linger.ms", "20ms"));
        parse("acks = \"2\"", Map.of("acks", "2"));
        parse("batch.size = -1", Map.of("batch.size", -1));

        // a misspelt name is accepted, and only a log line reports it
        Map<String, Object> props = base();
        props.put("lingr.ms", "50");
        new KafkaProducer<String, String>(props).close();
        log.list.stream()
                .filter(e -> e.getFormattedMessage().contains("not used"))
                .forEach(e -> System.out.println(e.getLevel() + " from " + e.getLoggerName()
                        + ":\n  " + e.getFormattedMessage()));
    }

    static void parse(String label, Map<String, Object> overrides) {
        Map<String, Object> props = base();
        props.putAll(overrides);
        try {
            ProducerConfig config = new ProducerConfig(props);
            System.out.printf("%-30s -> linger.ms=%d, acks=%s%n", label,
                    config.getLong("linger.ms"), config.getString("acks"));
        } catch (ConfigException e) {
            System.out.printf("%-30s -> ConfigException: %s%n", label, e.getMessage());
        }
    }

    static Map<String, Object> base() {
        Map<String, Object> props = new HashMap<>();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        return props;
    }
}
Output
linger.ms: type LONG, default 5, importance MEDIUM
acks: type STRING, valid values [all, -1, 0, 1]
linger.ms as the string "20"   -> linger.ms=20, acks=-1
linger.ms as the int 20        -> linger.ms=20, acks=-1
linger.ms = "20ms"             -> ConfigException: Invalid value 20ms for configuration linger.ms: Not a number of type LONG
acks = "2"                     -> ConfigException: Invalid value 2 for configuration acks: String must be one of: all, -1, 0, 1
batch.size = -1                -> ConfigException: Invalid value -1 for configuration batch.size: Value must be at least 0
INFO from org.apache.kafka.common.config.AbstractConfig:
  These configurations '[lingr.ms]' were supplied but are not used yet.
  • The ConfigDef entry says linger.ms is a LONG with default 5, and acks a STRING limited to all, -1, 0 and 1.
  • The string "20" and the int 20 both became the long 20. Values read from a properties file are strings, so every setting accepts its text form.
  • "20ms" was refused: "Not a number of type LONG". Kafka's time settings take plain numbers of milliseconds, not durations with units.
  • acks="2" and batch.size=-1 failed their validators with clear messages. These checks happen in the constructor, before any connection is made.
  • The misspelt lingr.ms was accepted without an error. The only trace was a log line, "These configurations '[lingr.ms]' were supplied but are not used yet", and it was logged at INFO level by AbstractConfig. An application that logs Kafka at WARN never sees it.

Use the constants from ProducerConfig and ConsumerConfig instead of string literals, so that the compiler catches typos. Unknown names are allowed on purpose: they are passed on to serializers, partitioners and interceptors, which read their own settings from the same map.

Keeping secrets out of the configuration

Passwords for SASL or TLS should not sit in a properties file next to the code. Config providers let a setting refer to a value stored elsewhere, and the client resolves the reference when it starts. Here a file stands in for a secrets volume:

Java
import ch.qos.logback.classic.Level;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.config.provider.FileConfigProvider;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ConfigProviders {

    public static void main(String[] args) throws Exception {
        // 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);
        // a secrets file, as a secret store or a Kubernetes volume would provide it
        Path dir = Files.createTempDirectory("kafka-secrets");
        Path secrets = dir.resolve("client.properties");
        Files.writeString(secrets, "username=order-service\npassword=s3cr3t-from-file\n");

        Map<String, Object> props = new HashMap<>();
        props.put("bootstrap.servers", "localhost:9092");
        props.put("key.serializer", StringSerializer.class);
        props.put("value.serializer", StringSerializer.class);
        props.put("config.providers", "file");
        props.put("config.providers.file.class", FileConfigProvider.class.getName());
        props.put("client.id", "${file:" + secrets + ":username}");
        props.put("sasl.jaas.config", "org.apache.kafka.common.security.plain.PlainLoginModule"
                + " required username=\"${file:" + secrets + ":username}\""
                + " password=\"${file:" + secrets + ":password}\";");

        ProducerConfig config = new ProducerConfig(props);
        System.out.println("written in the code : client.id = "
                + props.get("client.id").toString().replace(dir.toString(), "<dir>"));
        System.out.println("resolved by Kafka   : client.id = " + config.getString("client.id"));
        String jaas = config.getPassword("sasl.jaas.config").value();
        System.out.println("resolved JAAS line  : " + jaas.substring(jaas.indexOf("username")));
        System.out.println("toString() of it    : " + config.getPassword("sasl.jaas.config"));

        Files.delete(secrets);
        Files.delete(dir);
    }
}
Output
written in the code : client.id = ${file:<dir>/client.properties:username}
resolved by Kafka   : client.id = order-service
resolved JAAS line  : username="order-service" password="s3cr3t-from-file";
toString() of it    : [hidden]
  • The code contained only the reference ${file:<path>:username}. FileConfigProvider read the properties file and replaced it with "order-service".
  • References work inside longer values too: the JAAS line received both the user name and the password from the file.
  • sasl.jaas.config has the type PASSWORD, so its toString() prints [hidden]. Clients log their whole configuration at start-up, and password-type values are masked there in the same way.

Kafka ships three providers: FileConfigProvider for properties files, DirectoryConfigProvider for one-file-per-secret directories such as Kubernetes secret volumes, and EnvVarConfigProvider for environment variables. Brokers and Kafka Connect use the same mechanism. The JVM system property org.apache.kafka.automatic.config.providers controls which providers may be used, so a platform can forbid them where untrusted users write configuration.

Topic and broker settings at runtime

Topic and dynamic broker settings are changed through the Admin API (or the kafka-configs.sh tool, which calls it) without restarting anything. The program creates a topic with one override, changes it in several ways, and prints each value together with its source:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.AlterConfigOp;
import org.apache.kafka.clients.admin.Config;
import org.apache.kafka.clients.admin.ConfigEntry;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.common.config.ConfigResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;

public class TopicConfigs {

    static final List<String> NAMES = List.of("retention.ms", "cleanup.policy",
            "max.message.bytes", "min.insync.replicas");
    static final ConfigResource TOPIC = new ConfigResource(ConfigResource.Type.TOPIC, "audit");
    static final ConfigResource ALL_BROKERS = new ConfigResource(ConfigResource.Type.BROKER, "");

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        try (Admin admin = Admin.create(Map.of("bootstrap.servers",
                broker.getBrokersAsString()))) {
            admin.createTopics(List.of(new NewTopic("audit", 1, (short) 1)
                    .configs(Map.of("retention.ms", "86400000")))).all().get();
            show(admin, "1. created with retention.ms set");

            alter(admin, TOPIC, new AlterConfigOp(new ConfigEntry("cleanup.policy", "compact"),
                    AlterConfigOp.OpType.APPEND));
            alter(admin, TOPIC, new AlterConfigOp(new ConfigEntry("retention.ms", null),
                    AlterConfigOp.OpType.DELETE));
            show(admin, "2. APPEND compact to cleanup.policy, DELETE retention.ms");

            // a cluster-wide default, changed at runtime without restarting brokers
            alter(admin, ALL_BROKERS, new AlterConfigOp(
                    new ConfigEntry("log.retention.ms", "3600000"), AlterConfigOp.OpType.SET));
            // brokers apply the change from the metadata log a moment later
            while (!describe(admin).get("retention.ms").value().equals("3600000")) {
                Thread.sleep(100);
            }
            show(admin, "3. SET log.retention.ms for all brokers");

            try {
                alter(admin, ALL_BROKERS, new AlterConfigOp(
                        new ConfigEntry("log.dirs", "/tmp/elsewhere"), AlterConfigOp.OpType.SET));
            } catch (Exception e) {
                System.out.println("4. SET log.dirs: " + e.getCause().getClass().getSimpleName()
                        + ": " + e.getCause().getMessage());
            }
            ConfigEntry hours = admin.describeConfigs(List.of(new ConfigResource(
                    ConfigResource.Type.BROKER, "0"))).all().get().values().iterator().next()
                    .get("log.retention.hours");
            System.out.println("5. broker 0 log.retention.hours = " + hours.value()
                    + ", read-only: " + hours.isReadOnly() + ", source " + hours.source());
        } finally {
            broker.destroy();
        }
    }

    static void alter(Admin admin, ConfigResource resource, AlterConfigOp op) throws Exception {
        Map<ConfigResource, Collection<AlterConfigOp>> change = Map.of(resource, List.of(op));
        admin.incrementalAlterConfigs(change).all().get();
    }

    static Config describe(Admin admin) throws Exception {
        return admin.describeConfigs(List.of(TOPIC)).all().get().get(TOPIC);
    }

    static void show(Admin admin, String step) throws Exception {
        Config config = describe(admin);
        System.out.println(step + ":");
        for (String name : NAMES) {
            ConfigEntry e = config.get(name);
            System.out.printf("   %-20s %-15s %s%n", name, e.value(), e.source());
        }
    }

    // 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 turned off.
        // 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.OFF);
        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
1. created with retention.ms set:
   retention.ms         86400000        DYNAMIC_TOPIC_CONFIG
   cleanup.policy       delete          DEFAULT_CONFIG
   max.message.bytes    1048588         DEFAULT_CONFIG
   min.insync.replicas  1               DYNAMIC_DEFAULT_BROKER_CONFIG
2. APPEND compact to cleanup.policy, DELETE retention.ms:
   retention.ms         604800000       DEFAULT_CONFIG
   cleanup.policy       delete,compact  DYNAMIC_TOPIC_CONFIG
   max.message.bytes    1048588         DEFAULT_CONFIG
   min.insync.replicas  1               DYNAMIC_DEFAULT_BROKER_CONFIG
3. SET log.retention.ms for all brokers:
   retention.ms         3600000         DYNAMIC_DEFAULT_BROKER_CONFIG
   cleanup.policy       delete,compact  DYNAMIC_TOPIC_CONFIG
   max.message.bytes    1048588         DEFAULT_CONFIG
   min.insync.replicas  1               DYNAMIC_DEFAULT_BROKER_CONFIG
4. SET log.dirs: InvalidRequestException: Cannot update these configs dynamically: Set(log.dirs)
5. broker 0 log.retention.hours = 168, read-only: true, source DEFAULT_CONFIG
  • After creation, retention.ms was 86400000 (one day) with source DYNAMIC_TOPIC_CONFIG: the topic's own override. The other settings came from defaults.
  • APPEND added "compact" to the list setting cleanup.policy, giving "delete,compact": old segments are deleted by age, and the rest is compacted by key. DELETE removed the retention override, and the value fell back to the 7-day default of 604800000.
  • Setting log.retention.ms for all brokers (the empty broker name) changed the topic's effective retention to 3600000, one hour, with source DYNAMIC_DEFAULT_BROKER_CONFIG. Every topic without its own override got the new value. The brokers applied it a moment after the call returned, which is why the program waits for it.
  • min.insync.replicas also shows DYNAMIC_DEFAULT_BROKER_CONFIG. Since Kafka 4.1, new clusters enable eligible leader replicas (KIP-966), and the controller then keeps a cluster-wide min.insync.replicas as a dynamic setting.
  • log.dirs cannot be changed at runtime: "Cannot update these configs dynamically". log.retention.hours is read-only too, while log.retention.ms was dynamic. When both exist, the ms form wins.

Use incrementalAlterConfigs, as here. The older alterConfigs replaced the whole set of overrides of a resource, so a call that set one value silently removed all others; it was deprecated, and the Admin interface of kafka-clients 4.2 no longer has it.

Durability: replication factor, min.insync.replicas and acks

Three settings decide whether an acknowledged record survives a broker failure: the topic's replication factor, its min.insync.replicas, and the producer's acks. This program needs two brokers, so it starts a two-broker cluster in the JVM, writes to a topic with two replicas, then stops the follower broker:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import kafka.server.BrokerServer;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.admin.TopicDescription;
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.Node;
import org.apache.kafka.common.TopicPartitionInfo;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;

public class DurabilitySettings {

    static String servers;

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaKraftBroker cluster = startBrokers(2);
        servers = cluster.getBrokersAsString();
        try (Admin admin = Admin.create(Map.of("bootstrap.servers", servers));
             KafkaProducer<String, String> acksAll = producer("all");
             KafkaProducer<String, String> acksOne = producer("1")) {
            try {
                admin.createTopics(List.of(new NewTopic("orders", 1, (short) 3))).all().get();
            } catch (ExecutionException e) {
                System.out.println("replication factor 3 on 2 brokers: "
                        + e.getCause().getClass().getSimpleName());
            }
            admin.createTopics(List.of(new NewTopic("payments", 1, (short) 2)
                    .configs(Map.of("min.insync.replicas", "2")))).all().get();
            describe(admin, "payments");
            // one replica only, placed on the broker that will stay up
            int leader = partition(admin, "payments").leader().id();
            admin.createTopics(List.of(new NewTopic("single", Map.of(0, List.of(leader)))
                    .configs(Map.of("min.insync.replicas", "2")))).all().get();
            send(acksAll, "payments", "all");
            send(acksOne, "payments", "1");
            send(acksAll, "single", "all"); // min.insync.replicas above the replication factor

            BrokerServer follower = cluster.getCluster().brokers().values().stream()
                    .filter(b -> b.config().nodeId() != leader).findFirst().orElseThrow();
            follower.shutdown();
            follower.awaitShutdown();
            System.out.println("broker " + follower.config().nodeId() + " stopped");
            while (partition(admin, "payments").isr().size() > 1) {
                Thread.sleep(200); // wait until the controller shrinks the ISR
            }
            describe(admin, "payments");
            send(acksAll, "payments", "all");
            send(acksOne, "payments", "1");
        }
        // the test kit can hang closing a cluster with a stopped broker, so end the JVM here
        System.exit(0);
    }

    static KafkaProducer<String, String> producer(String acks) {
        return new KafkaProducer<>(Map.of(
                "bootstrap.servers", servers,
                "acks", acks,
                "request.timeout.ms", 1000,
                "delivery.timeout.ms", 3000,
                "key.serializer", StringSerializer.class,
                "value.serializer", StringSerializer.class));
    }

    static void send(KafkaProducer<String, String> producer, String topic, String acks) {
        try {
            RecordMetadata meta = producer.send(new ProducerRecord<>(topic, "100 EUR")).get();
            System.out.println("   acks=" + acks + " to " + topic + ": written at offset "
                    + meta.offset());
        } catch (ExecutionException e) {
            System.out.println("   acks=" + acks + " to " + topic + ": "
                    + e.getCause().getClass().getSimpleName() + ": " + e.getCause().getMessage());
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    static TopicPartitionInfo partition(Admin admin, String topic) throws Exception {
        TopicDescription d = admin.describeTopics(List.of(topic)).allTopicNames().get().get(topic);
        return d.partitions().get(0);
    }

    static void describe(Admin admin, String topic) throws Exception {
        TopicPartitionInfo p = partition(admin, topic);
        System.out.println(topic + ": leader " + p.leader().id() + ", replicas "
                + p.replicas().stream().map(Node::id).toList() + ", in sync "
                + p.isr().stream().map(Node::id).toList());
    }

    // Starts a KRaft cluster of n brokers inside this JVM, from spring-kafka-test
    static EmbeddedKafkaKraftBroker startBrokers(int n) {
        // the brokers log at INFO and print their storage setup, so both are turned off.
        // 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.OFF);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            EmbeddedKafkaKraftBroker cluster = new EmbeddedKafkaKraftBroker(n, 1);
            cluster.brokerProperties(Map.of("transaction.state.log.replication.factor", "1",
                    "transaction.state.log.min.isr", "1"));
            cluster.afterPropertiesSet();
            return cluster;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
replication factor 3 on 2 brokers: InvalidReplicationFactorException
payments: leader 0, replicas [0, 1], in sync [0, 1]
   acks=all to payments: written at offset 0
   acks=1 to payments: written at offset 1
   acks=all to single: written at offset 0
broker 1 stopped
payments: leader 0, replicas [0, 1], in sync [0]
   acks=all to payments: TimeoutException: Expiring 1 record(s) for payments-0:3002 ms has passed since batch creation
   acks=1 to payments: written at offset 2
  • A replication factor of 3 on two brokers was refused at creation with InvalidReplicationFactorException. Kafka never puts two replicas of a partition on one broker.
  • With both brokers up, both replicas of payments were in sync, and writes with acks=all and acks=1 succeeded.
  • The single topic has one replica but min.insync.replicas=2, and the acks=all write still succeeded. KIP-966 made the effective minimum the smaller of min.insync.replicas and the replication factor, so a minimum above the replication factor no longer has any effect.
  • After the follower stopped, the in-sync set shrank to the leader alone. An acks=all write now needed two in-sync copies and got only one. The broker rejected it with the error NOT_ENOUGH_REPLICAS (the producer logs each retry at WARN level, turned off here). The error is retriable, so the producer kept retrying until delivery.timeout.ms (3 seconds here) ran out and the record expired with a TimeoutException.
  • The acks=1 write succeeded at once, at offset 2, with only one copy. Had the leader failed next, that record would have been lost.

The usual production choice is a replication factor of 3, min.insync.replicas=2 and acks=all: any one broker can fail without stopping writes or losing acknowledged data. With two replicas and a minimum of 2, as here, a single failure stops all acks=all writes. The program ends with System.exit, because the test harness can hang while closing a cluster with a stopped broker.

Settings worth knowing

Most defaults are sensible. These are the settings most often changed, with the values Kafka 4.2 uses when they are not set:

Important producer, consumer and topic settings
SettingDefaultChange it when
Producer acksallLosing records is acceptable for speed (idempotence then turns off)
Producer linger.ms, batch.size5, 16384Throughput matters more than a few ms of latency
Producer compression.typenoneAlmost always: lz4 or zstd
Producer delivery.timeout.ms120000Callers must learn of failures sooner
Consumer auto.offset.resetlatestA new group must read existing data
Consumer enable.auto.committrueOffsets must only be committed after processing
Consumer max.poll.records, max.poll.interval.ms500, 300000Processing a batch can take longer than 5 minutes
Consumer isolation.levelread_uncommittedThe topic is written by transactional producers
Consumer group.protocolclassicFaster, incremental rebalances are wanted (consumer)
Topic retention.ms604800000 (7 days)Data must be kept longer, or disk is short
Topic cleanup.policydeleteOnly the latest value per key matters (compact)
Topic min.insync.replicas1Durability matters: 2 with a replication factor of 3

Choosing where to set a value

Situations and the configuration level that fits
SituationWhere to set it
One application's batching, timeouts or commitsClient settings, with the ProducerConfig and ConsumerConfig constants
One topic needs longer retention or compactionA topic override, at creation or with incrementalAlterConfigs
Every topic should change at once, without restartsA dynamic default for all brokers
Disk paths, node ids, rolesserver.properties, with a restart
Passwords and keysA config provider reference, never the literal value
Durable writesReplication factor 3 and min.insync.replicas=2 on the topic, acks=all on the producer

The settings themselves are explained where they matter: producers, consumers, topics and partitions and offsets. Securing clients with TLS and SASL is covered on the Kafka security page, and Spring Boot's spring.kafka.* properties on KafkaTemplate.