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.
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.msretention.ms
| Level | Set where | Changed how | Examples |
|---|---|---|---|
| Client | The PropertiesMap | Restart the client | ackslinger.msgroup.idmax.poll.records |
| Topic | Topic creation, or incrementalAlterConfigs | At runtime | retention.mscleanup.policymin.insync.replicas |
| Broker, dynamic | The Admin | At runtime, stored in the cluster metadata | log.retention.msnum.io.threads |
| Broker, static | server.properties | Restart the broker | log.dirsprocess.rolesnode.id |
| Group | The Admin | At runtime | share.auto.offset.resetconsumer.session.timeout.ms |
Many topic settings have a broker-side default with a different name: the topic's retention.mslog.retention.msmax.message.bytesmessage.max.bytesserver.properties
On the client side, every setting is declared in a ConfigDefProducerConfigConsumerConfigAdminClientConfigProducerConfig.LINGER_MS_CONFIGkafka-clientsEmbeddedKafkaKraftBrokerspring-kafka-test
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:
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;
}
}
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
entry saysConfigDef is alinger.ms with default 5, andLONG aacks limited to all, -1, 0 and 1.STRING - 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.
andacks="2" failed their validators with clear messages. These checks happen in the constructor, before any connection is made.batch.size=-1- The misspelt
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 bylingr.ms . An application that logs Kafka at WARN never sees it.AbstractConfig
Use the constants from ProducerConfigConsumerConfig
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:
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);
}
}
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} read the properties file and replaced it with "order-service".FileConfigProvider - References work inside longer values too: the JAAS line received both the user name and the password from the file.
has the typesasl.jaas.config , so itsPASSWORD printstoString() . Clients log their whole configuration at start-up, and password-type values are masked there in the same way.[hidden]
Kafka ships three providers: FileConfigProviderDirectoryConfigProviderEnvVarConfigProviderorg.apache.kafka.automatic.config.providers
Topic and broker settings at runtime
Topic and dynamic broker settings are changed through the Adminkafka-configs.sh
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);
}
}
}
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,
was 86400000 (one day) with sourceretention.ms : the topic's own override. The other settings came from defaults.DYNAMIC_TOPIC_CONFIG added "compact" to the list settingAPPEND , giving "delete,compact": old segments are deleted by age, and the rest is compacted by key.cleanup.policy removed the retention override, and the value fell back to the 7-day default of 604800000.DELETE- Setting
for all brokers (the empty broker name) changed the topic's effective retention to 3600000, one hour, with sourcelog.retention.ms . 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.DYNAMIC_DEFAULT_BROKER_CONFIG also showsmin.insync.replicas . Since Kafka 4.1, new clusters enable eligible leader replicas (KIP-966), and the controller then keeps a cluster-wideDYNAMIC_DEFAULT_BROKER_CONFIG as a dynamic setting.min.insync.replicas cannot be changed at runtime: "Cannot update these configs dynamically".log.dirs is read-only too, whilelog.retention.hours was dynamic. When both exist, thelog.retention.ms form wins.ms
Use incrementalAlterConfigsalterConfigsAdmin
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.replicasacks
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);
}
}
}
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
. Kafka never puts two replicas of a partition on one broker.InvalidReplicationFactorException - With both brokers up, both replicas of
were in sync, and writes withpayments andacks=all succeeded.acks=1 - The
topic has one replica butsingle , and themin.insync.replicas=2 write still succeeded. KIP-966 made the effective minimum the smaller ofacks=all and the replication factor, so a minimum above the replication factor no longer has any effect.min.insync.replicas - After the follower stopped, the in-sync set shrank to the leader alone. An
write now needed two in-sync copies and got only one. The broker rejected it with the erroracks=all (the producer logs each retry at WARN level, turned off here). The error is retriable, so the producer kept retrying untilNOT_ENOUGH_REPLICAS (3 seconds here) ran out and the record expired with adelivery.timeout.ms .TimeoutException - The
write succeeded at once, at offset 2, with only one copy. Had the leader failed next, that record would have been lost.acks=1
The usual production choice is a replication factor of 3, min.insync.replicas=2acks=allacks=allSystem.exit
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:
| Setting | Default | Change it when |
|---|---|---|
Producer acks | all | Losing records is acceptable for speed (idempotence then turns off) |
Producer linger.msbatch.size | 5, 16384 | Throughput matters more than a few ms of latency |
Producer compression.type | none | Almost always: lz4 or zstd |
Producer delivery.timeout.ms | 120000 | Callers must learn of failures sooner |
Consumer auto.offset.reset | latest | A new group must read existing data |
Consumer enable.auto.commit | true | Offsets must only be committed after processing |
Consumer max.poll.recordsmax.poll.interval.ms | 500, 300000 | Processing a batch can take longer than 5 minutes |
Consumer isolation.level | read_uncommitted | The topic is written by transactional producers |
Consumer group.protocol | classic | Faster, incremental rebalances are wanted (consumer |
Topic retention.ms | 604800000 (7 days) | Data must be kept longer, or disk is short |
Topic cleanup.policy | delete | Only the latest value per key matters (compact |
Topic min.insync.replicas | 1 | Durability matters: 2 with a replication factor of 3 |
Choosing where to set a value
| Situation | Where to set it |
|---|---|
| One application's batching, timeouts or commits | Client settings, with the ProducerConfigConsumerConfig |
| One topic needs longer retention or compaction | A topic override, at creation or with incrementalAlterConfigs |
| Every topic should change at once, without restarts | A dynamic default for all brokers |
| Disk paths, node ids, roles | server.properties |
| Passwords and keys | A config provider reference, never the literal value |
| Durable writes | Replication factor 3 and min.insync.replicas=2acks=all |
The settings themselves are explained where they matter: spring.kafka.*