Kafka KRaft Cluster Setup: Production Guide with Compose
Set up a Kafka KRaft cluster for production: controller quorum, storage format, ACLs, monitoring, backups, Docker Compose and Strimzi, tested on Kafka 4.4.
On this page · 15 sections
- The topology to start from
- Sizing hardware
- OS settings
- Configuration that matters
- Formatting storage and starting the quorum
- Security
- Monitoring
- Client settings
- Failure drills
- Backup and recovery
- Docker Compose: three controllers and three brokers
- Kubernetes with Strimzi
- Troubleshooting
- Production checklist
- Where to go next
Setting up a Kafka KRaft cluster for production is mostly about deciding, before the first incident, what happens when a broker, a disk or a whole zone dies. This guide is written for Kafka 4.x in KRaft mode, which is the only mode there is now: Kafka 4.0 removed ZooKeeper, so a cluster is brokers plus a small quorum of Kafka controllers, and every admin tool talks to it with --bootstrap-server. If you are still on ZooKeeper, you have to migrate to KRaft on a 3.x release (3.9 is the last bridge) before you can upgrade to 4.x.
Everything marked “run” below was run on 4 Dec 2026 on one Linux box with the Apache Kafka 4.4.0 tarball (OpenJDK 21) and the apache/kafka:4.4.0 Docker image. The Kubernetes manifest and the TLS, JMX exporter and MirrorMaker settings were not run, and say so where they appear. Configs and scripts are in course-code/kafka-mastery/production-kraft/ in the site repo.
The topology to start from
Clients (producers, consumers, Connect, Streams)
│ bootstrap list: broker-1:9092,broker-2:9092,broker-3:9092
│ then direct connections to each partition leader
▼
┌──────────────── Brokers (data plane) ────────────────┐
│ broker-4 (zone a) broker-5 (zone b) broker-6 (zone c) │
│ partitions, replication, consumer group coordination │
└───────────────────────────┬──────────────────────────┘
│ metadata fetch, heartbeats
┌──────────── Controllers (KRaft quorum) ──────────────┐
│ controller-1 (a) controller-2 (b) controller-3 (c) │
│ __cluster_metadata log, one active controller │
└──────────────────────────────────────────────────────┘
Three decisions are baked into that picture:
- Dedicated controllers, three of them. A Raft quorum of 3 survives one controller loss; 5 survives two and is worth it only for very large clusters or when you can’t replace a node within hours. Combined mode (
process.roles=broker,controller) works and is what I used for the local drills, but in production it ties metadata availability to data-plane load: a broker drowning in GC pauses or a full disk also stalls the quorum. Section Failure drills shows the practical difference. - No load balancer in the data path. Kafka clients fetch metadata and then connect straight to the broker that leads each partition. A load balancer in front of the brokers is only useful as a stable bootstrap address, and each broker still has to advertise an address the client can reach directly (
advertised.listeners). - One broker per zone, replication factor 3,
min.insync.replicas=2. Setbroker.rackto the zone so the three replicas of a partition land in three zones. Then losing a zone costs you one replica per partition and nothing else.
Sizing hardware
Size disk from your data, not from a template. The arithmetic for a cluster that ingests 50 MB/s and keeps 3 days:
50 MB/s × 86,400 s = 4.32 TB/day of new data
× 3 days retention = 12.96 TB
× replication factor 3 = 38.9 TB on disk across the cluster
÷ 6 brokers = 6.5 TB per broker
+ 30% headroom ≈ 8.4 TB usable per broker
Network follows the same logic. Each byte produced is written once by the leader and copied twice to followers, and every consumer group reads it once more. With three consumer groups, 50 MB/s in becomes 100 MB/s of replication and 150 MB/s of consumer reads, spread across the brokers. A 10 Gbps NIC (about 1.2 GB/s) has room for that on six brokers; catch-up reads after an outage are what fill it.
Starting points for brokers:
- CPU: 8 to 16 cores. TLS and compression are what use them.
- Memory: 32 to 64 GB, of which the JVM heap gets about 6 GB. The rest is page cache, which is what serves consumers reading near the tail without touching disk. A 16 GB heap does not make Kafka faster; it makes G1 pauses longer and takes memory away from the page cache.
- Disk: local NVMe or SSD-backed volumes with XFS or ext4. RAID 10 or JBOD (multiple
log.dirs) both work; JBOD gives more capacity, RAID 10 makes single-disk failure invisible to Kafka. Don’t use NFS.
Controllers are small: 4 cores, 8 GB of RAM with a 1 to 2 GB heap, and a fast SSD of 20 to 50 GB for the metadata log. What matters is low fsync latency and not sharing a disk with something noisy.
OS settings
# /etc/sysctl.d/90-kafka.conf
vm.swappiness = 1
vm.max_map_count = 262144 # each log segment maps its index files; the default 65530 runs out
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.core.netdev_max_backlog = 5000
# /etc/security/limits.d/kafka.conf (or LimitNOFILE= in the systemd unit)
kafka - nofile 100000
vm.max_map_count is the one people forget. A broker with 4,000 partitions and a few segments each needs more memory maps than the default allows, and the symptom is an OutOfMemoryError: Map failed that has nothing to do with heap.
Configuration that matters
Controllers
# controller.properties (controller-1)
process.roles=controller
node.id=1
controller.quorum.bootstrap.servers=controller-1:9093,controller-2:9093,controller-3:9093
listeners=CONTROLLER://:9093
advertised.listeners=CONTROLLER://controller-1:9093
controller.listener.names=CONTROLLER
listener.security.protocol.map=CONTROLLER:SSL
log.dirs=/var/lib/kafka/metadata
# Topic-creation defaults are applied by the active controller, not the broker.
default.replication.factor=3
num.partitions=6
min.insync.replicas=2
authorizer.class.name=org.apache.kafka.metadata.authorizer.StandardAuthorizer
super.users=User:kafka-controller;User:kafka-broker;User:admin
The comment in the middle is a real trap. With KRaft, CreateTopics is handled by the controller, so when a client creates a topic without saying how many replicas it wants, the controller’s default.replication.factor decides. I hit this in the Compose test below: the brokers had default.replication.factor=3, the controllers didn’t, and kafka-topics.sh --create --topic orders --partitions 6 produced this:
Topic: orders TopicId: n1kso_WhSGSU4npkTQqqMw PartitionCount: 6 ReplicationFactor: 1 Configs: min.insync.replicas=1
A replication factor of 1 in production means one disk failure loses data. Set the defaults on the controllers as well, and pass --replication-factor explicitly in your topic tooling anyway.
Brokers
# broker.properties (broker-4)
process.roles=broker
node.id=4
broker.rack=zone-a
controller.quorum.bootstrap.servers=controller-1:9093,controller-2:9093,controller-3:9093
controller.listener.names=CONTROLLER
listeners=INTERNAL://:19092,EXTERNAL://:9092
advertised.listeners=INTERNAL://broker-4.internal:19092,EXTERNAL://broker-4.example.com:9092
inter.broker.listener.name=INTERNAL
listener.security.protocol.map=CONTROLLER:SSL,INTERNAL:SASL_SSL,EXTERNAL:SASL_SSL
log.dirs=/data1/kafka,/data2/kafka
default.replication.factor=3
min.insync.replicas=2
offsets.topic.replication.factor=3
transaction.state.log.replication.factor=3
transaction.state.log.min.isr=2
unclean.leader.election.enable=false
auto.create.topics.enable=false
num.network.threads=8
num.io.threads=16
log.retention.hours=168
log.segment.bytes=1073741824
authorizer.class.name=org.apache.kafka.metadata.authorizer.StandardAuthorizer
super.users=User:kafka-controller;User:kafka-broker;User:admin
What changed from a ZooKeeper-era file: broker.id became node.id (unique across brokers and controllers), zookeeper.connect is gone and replaced by controller.quorum.bootstrap.servers, and the broker needs controller.listener.names to know which listener and security protocol to use when it talks to the controllers.
Two settings from older guides that I removed on purpose. log.retention.bytes is a per-partition limit, so a broker-wide log.retention.bytes=1073741824 caps every partition at 1 GiB and quietly overrides your seven days of retention on any busy topic; set size limits per topic if you need them. And there’s no reason to lower replica.lag.time.max.ms from its default of 30 s: a smaller value makes followers drop out of the ISR on every GC pause, and producers with acks=all then pay for the ISR churn.
JVM
export KAFKA_HEAP_OPTS="-Xms6g -Xmx6g"
# kafka-run-class.sh already defaults to G1 with MaxGCPauseMillis=20 and
# InitiatingHeapOccupancyPercent=35; override KAFKA_JVM_PERFORMANCE_OPTS only with a reason.
Formatting storage and starting the quorum
A KRaft node won’t start until its log directory has been formatted with the cluster ID. Generate the ID once and use it everywhere:
CLUSTER_ID=$(bin/kafka-storage.sh random-uuid)
Kafka 4.x supports a dynamic controller quorum (KIP-853), where controllers can be added and removed at runtime. You opt in by using controller.quorum.bootstrap.servers instead of the older static controller.quorum.voters, and then format refuses to guess. This is what you get if you leave out the quorum flag (run):
Because controller.quorum.voters is not set on this controller, you must specify one of the following: --standalone, --initial-controllers, or --no-initial-controllers.
For a three-controller cluster, give every controller the full initial voter set, each with a pre-generated directory ID, and format brokers with --no-initial-controllers:
# one directory ID per controller, generated once
D1=$(bin/kafka-storage.sh random-uuid); D2=$(bin/kafka-storage.sh random-uuid); D3=$(bin/kafka-storage.sh random-uuid)
IC="1@controller-1:9093:$D1,2@controller-2:9093:$D2,3@controller-3:9093:$D3"
# on each controller
bin/kafka-storage.sh format --cluster-id "$CLUSTER_ID" --config controller.properties --initial-controllers "$IC"
# on each broker
bin/kafka-storage.sh format --cluster-id "$CLUSTER_ID" --config broker.properties --no-initial-controllers
For the local drills I ran three combined nodes on one machine (ports 19092/19093, 29092/29093, 39092/39093). After formatting and starting all three, the quorum looked like this (run):
$ bin/kafka-metadata-quorum.sh --bootstrap-server localhost:19092 describe --status
ClusterId: pZwi_RZZSSuvLVHAWs0VpQ
LeaderId: 1
LeaderEpoch: 1
HighWatermark: 59
MaxFollowerLag: 0
MaxFollowerLagTimeMs: 0
CurrentVoters: [{"id": 1, "directoryId": "yZGOxtMPQ6mFf7lsgF8T9A", "endpoints": ["CONTROLLER://localhost:19093"]}, {"id": 2, "directoryId": "2KZpfWMmQkSqiKkmV8_HPQ", "endpoints": ["CONTROLLER://localhost:29093"]}, {"id": 3, "directoryId": "FAOpWsRAQmuvmVrXWMNeyA", "endpoints": ["CONTROLLER://localhost:39093"]}]
CurrentObservers: []
Brokers show up as observers in describe --replication (they replicate the metadata log but don’t vote); you’ll see that in the Compose output further down. Make describe --status part of your deploy check: three voters, one leader, MaxFollowerLag near 0.
Formatting is also a safety check. Running it again on a directory that already has data fails instead of wiping it (run):
Log directory /workspace/kafka-prod-0412/data1 is already formatted. Use --ignore-formatted to ignore this directory and format the others.
Security
Encrypt and authenticate every listener, including the controller listener. A TLS listener with SASL/SCRAM for clients (not run here; the security lesson walks through certificates and SCRAM users):
listener.security.protocol.map=CONTROLLER:SSL,INTERNAL:SASL_SSL,EXTERNAL:SASL_SSL
sasl.enabled.mechanisms=SCRAM-SHA-512
sasl.mechanism.inter.broker.protocol=SCRAM-SHA-512
ssl.keystore.type=PKCS12
ssl.keystore.location=/etc/kafka/tls/broker-4.p12
ssl.keystore.password=${file:/etc/kafka/secrets.properties:keystore.password}
ssl.truststore.type=PKCS12
ssl.truststore.location=/etc/kafka/tls/truststore.p12
ssl.truststore.password=${file:/etc/kafka/secrets.properties:truststore.password}
ssl.enabled.protocols=TLSv1.3,TLSv1.2
config.providers=file
config.providers.file.class=org.apache.kafka.common.config.provider.FileConfigProvider
Keep passwords out of server.properties with the FileConfigProvider as above, so the file can live in version control.
ACLs live in the metadata log and are enforced by StandardAuthorizer. The ZooKeeper-based AclAuthorizer was removed in 4.0, along with the kafka-acls.sh --authorizer-properties option that older guides use to write ACLs straight into ZooKeeper; on 4.4.0 the tool rejects it with authorizer-properties is not a recognized option (run). Manage ACLs through the brokers instead (run, against the three-node test cluster with StandardAuthorizer):
bin/kafka-acls.sh --bootstrap-server localhost:19092 --add \
--allow-principal User:producer --operation Write --operation Describe --topic user-events
bin/kafka-acls.sh --bootstrap-server localhost:19092 --add \
--allow-principal User:consumer --operation Read --topic user-events --group analytics-group
Adding ACLs for resource `ResourcePattern(resourceType=TOPIC, name=user-events, patternType=LITERAL)`:
(principal=User:producer, host=*, operation=DESCRIBE, permissionType=ALLOW)
(principal=User:producer, host=*, operation=WRITE, permissionType=ALLOW)
Adding ACLs for resource `ResourcePattern(resourceType=GROUP, name=analytics-group, patternType=LITERAL)`:
(principal=User:consumer, host=*, operation=READ, permissionType=ALLOW)
Adding ACLs for resource `ResourcePattern(resourceType=TOPIC, name=user-events, patternType=LITERAL)`:
(principal=User:consumer, host=*, operation=READ, permissionType=ALLOW)
A consumer needs Read on both the topic and its group, which is why the second command adds two bindings. Avoid the “admin can do anything” ACL (--operation All --topic '*' --group '*') that older guides start with; put admins in super.users and give every application only what it uses. The test cluster ran with super.users=User:ANONYMOUS on a plaintext listener so the commands could run without certificates, so ACL enforcement wasn’t exercised here.
Monitoring
Kafka exposes metrics over JMX, not HTTP. Port 9092 speaks the Kafka protocol, and pointing Prometheus at broker:9092/metrics or at the raw JMX port returns nothing useful. Attach the Prometheus JMX exporter as a Java agent on every broker and controller (not run here):
export KAFKA_OPTS="-javaagent:/opt/jmx_prometheus_javaagent.jar=7071:/opt/kafka-jmx-exporter.yml"
# prometheus.yml
scrape_configs:
- job_name: kafka
scrape_interval: 15s
static_configs:
- targets: ['broker-4:7071', 'broker-5:7071', 'broker-6:7071',
'controller-1:7071', 'controller-2:7071', 'controller-3:7071']
The metrics worth alerting on, read with kafka-jmx.sh from node 1 of the test cluster while it was a follower (run):
name=ActiveControllerCount:Value=0
name=OfflinePartitionsCount:Value=0
name=UnderMinIsrPartitionCount:Value=0
name=UnderReplicatedPartitions:Value=0
kafka.server:type=raft-metrics:current-leader=2
kafka.server:type=raft-metrics:current-state=follower
kafka.server:type=raft-metrics:high-watermark=299
| MBean | Alert when |
|---|---|
kafka.controller:type=KafkaController,name=ActiveControllerCount | sum across controllers ≠ 1 for more than a minute |
kafka.controller:type=KafkaController,name=OfflinePartitionsCount | > 0 (partitions with no leader; producers to them fail) |
kafka.server:type=ReplicaManager,name=UnderMinIsrPartitionCount | > 0 (acks=all writes to these partitions are being rejected) |
kafka.server:type=ReplicaManager,name=UnderReplicatedPartitions | > 0 for more than a few minutes outside a deploy |
kafka.network:type=RequestMetrics,name=TotalTimeMs,request=Produce | p99 well above your baseline |
kafka.server:type=raft-metrics current-state | a controller stuck in candidate or unattached |
Disk free on every log.dirs mount | < 25% |
Consumer lag isn’t a broker metric. Get it from kafka-consumer-groups.sh --describe, from the kafka_consumergroup_lag series of kafka_exporter, or from the client’s own records-lag-max. The lag lesson builds a lag check you can alert on, and Kafka monitoring best practices covers dashboards.
Client settings
Kafka 4.x defaults are already safe. These are the producer defaults on 4.4.0, read from ProducerConfig (run):
acks all
enable.idempotence true
retries 2147483647
delivery.timeout.ms 120000 (2 minutes)
linger.ms 5
batch.size 16384
compression.type none
So the production producer config is mostly about throughput and not undoing the safety:
Properties props = new Properties();
props.put("bootstrap.servers", "broker-4:9092,broker-5:9092,broker-6:9092");
props.put("acks", "all"); // the default; say it so nobody "optimizes" it to 1
props.put("linger.ms", 10); // default 5; a bit more batching at high volume
props.put("batch.size", 131072); // 128 KB batches instead of 16 KB
props.put("compression.type", "lz4"); // or zstd for better ratio at more CPU
Two things older guides get wrong. acks=1 is not a free speed-up: setting it also silently turns idempotence off (idempotence requires acks=all), so retries can write duplicates, and a leader crash can lose writes the producer already saw acknowledged. And retries=3 overrides a default that was chosen on purpose; let delivery.timeout.ms bound the retrying instead. The producers lesson measures what batching and compression actually buy.
For consumers, keep enable.auto.commit=false and commit after processing, raise max.poll.records only as far as you can process inside max.poll.interval.ms, and give each consumer a stable group.instance.id if you deploy with rolling restarts. The consumer lesson and the rebalancing lesson explain why.
Create topics explicitly with the settings you mean (run):
bin/kafka-topics.sh --bootstrap-server localhost:19092 --create --topic user-events \
--partitions 12 --replication-factor 3 \
--config min.insync.replicas=2 --config retention.ms=604800000 \
--config segment.ms=3600000 --config compression.type=snappy
Created topic user-events.
Topic: user-events TopicId: gylUHXC1Q86dKPmOxkqH_A PartitionCount: 12 ReplicationFactor: 3 Configs: compression.type=snappy,min.insync.replicas=2,retention.ms=604800000,unclean.leader.election.enable=false,segment.ms=3600000
Topic: user-events Partition: 0 Leader: 3 Replicas: 3,1,2 Isr: 3,1,2 Elr: LastKnownElr:
How many partitions to choose is its own question; Kafka partitions works through it.
Failure drills
Run these on a staging cluster before production and write down what you saw. These are the numbers from the box.
Killing the active controller
With the three-node cluster up and node 1 as quorum leader, I ran kill -9 on node 1 and polled describe --status from node 2 (run):
new leader 2 after 3460 ms (incl. CLI startup)
[2026-12-04 10:01:53,976] INFO [RaftManager id=2] Completed transition to Leader(...)
The broker logs show node 1 disconnecting at 10:01:50.92, so the new controller was elected about 3 seconds after the crash. Metadata changes (topic creation, leader elections) wait during that gap; produce and fetch to partitions led by surviving brokers keep working.
One broker down, then two
Still with node 1 dead, 1,000 records went in with acks=all. Partition 3 is led by node 3, but node 1 was still in its ISR, so acks=all writes waited for a replica that would never answer until the controller fenced node 1 (broker.session.timeout.ms, 9 s by default) and dropped it from the ISR. The console producer’s 1.5 s request timeout expired three times in that window:
WARN ... Got error produce response with correlation id 7 on topic-partition user-events-3, retrying (2 attempts left). Error: REQUEST_TIMED_OUT
All 1,000 records landed, and the ISR showed two replicas per partition, which still meets min.insync.replicas=2.
To see the other side of that setting I used the Compose cluster (dedicated controllers, brokers 4–6), stopped two of the three brokers and produced again (run):
WARN ... Got error produce response with correlation id 5 on topic-partition payments-5, retrying (2 attempts left). Error: NOT_ENOUGH_REPLICAS
Topic: payments Partition: 0 Leader: 4 Replicas: 6,4,5 Isr: 4 Elr: 5 LastKnownElr:
That’s the trade you’re making with RF 3 / min.insync.replicas=2: with two of three replicas gone, Kafka refuses writes rather than accept data that lives on a single disk. Reads still worked, and because the controllers were separate machines the quorum was fine (LeaderId: 2), so the cluster recovered as soon as a broker came back. In combined mode, losing two of three nodes would also have lost the controller majority. The Elr: 5 column is Kafka 4’s eligible leader replicas: broker 5 was in sync when the ISR shrank below the minimum, so the controller knows it can become leader without losing committed data.
Backup and recovery
Kafka’s replication is the backup for broker disks. What you still need to protect is the stuff a rebuilt cluster can’t recreate on its own, and a second copy of the data in another region if a region outage is in scope.
What a nightly export should contain
ZooKeeper-era guides back up /var/lib/zookeeper with tar. In KRaft the equivalent state (topics, configs, ACLs, SCRAM credentials, quotas) is in the __cluster_metadata log on the controllers, and the practical backup is to export it through the admin API so you can recreate it on a new cluster:
#!/usr/bin/env bash
set -euo pipefail
B=${BOOTSTRAP:-localhost:19092}
K=${KAFKA_BIN:-kafka/bin}
OUT=kafka-meta-$(date +%Y%m%d-%H%M)
mkdir -p "$OUT"
$K/kafka-topics.sh --bootstrap-server "$B" --describe > "$OUT/topics.txt"
$K/kafka-configs.sh --bootstrap-server "$B" --describe --entity-type topics > "$OUT/topic-configs.txt"
$K/kafka-configs.sh --bootstrap-server "$B" --describe --entity-type brokers --entity-default > "$OUT/broker-default-configs.txt"
$K/kafka-acls.sh --bootstrap-server "$B" --list > "$OUT/acls.txt"
$K/kafka-consumer-groups.sh --bootstrap-server "$B" --describe --all-groups --offsets > "$OUT/group-offsets.txt" 2>/dev/null
$K/kafka-metadata-quorum.sh --bootstrap-server "$B" describe --status > "$OUT/quorum.txt"
wc -l "$OUT"/*
Run against the test cluster with one topic, four ACLs and one consumer group:
8 kafka-meta-20261204-1003/acls.txt
2 kafka-meta-20261204-1003/broker-default-configs.txt
14 kafka-meta-20261204-1003/group-offsets.txt
8 kafka-meta-20261204-1003/quorum.txt
9 kafka-meta-20261204-1003/topic-configs.txt
64 kafka-meta-20261204-1003/topics.txt
105 total
Better still, keep topics and ACLs as code (Terraform, Strimzi KafkaTopic/KafkaUser, or your own scripts) and treat this export as the check that the code still matches the cluster. SCRAM passwords can’t be exported in clear text; keep them in your secret store.
Reading a copy of the metadata log
A file copy of a controller’s __cluster_metadata-0 directory is useful for forensics: you can open it offline with kafka-metadata-shell.sh and see exactly what the cluster believed. On the test cluster (run):
$ cp -r data2/__cluster_metadata-0 backup/
$ bin/kafka-metadata-shell.sh --snapshot backup/__cluster_metadata-0/00000000000000000000.log ls /image/topics/byName
user-events
$ bin/kafka-metadata-shell.sh --snapshot backup/__cluster_metadata-0/00000000000000000000.log ls /image/acls/byId
01jQsKIpTVuU21dx8XS0yw
1cDkai6BSe6dgBK_U2Feow
i0ACxQ8PQK26_RflftOzlA
tZCiMqazRv6YDqXNpnkyfA
(The shell also prints ERROR Ignoring control record with type KRAFT_VOTERS lines on 4.4.0; they’re harmless.) Don’t plan to restore a cluster by copying this directory back. The metadata log is tied to the cluster ID and the voter set, and a restored old copy would be behind the brokers’ view of the world. Recovery means replacing failed controllers so the surviving quorum re-replicates the log, which is the next drill.
Replacing a controller whose disk died
This is the KRaft operation to rehearse. On the test cluster I killed node 3, deleted its whole data directory, and reformatted it as a node that doesn’t claim a voter slot (run):
kill -9 <node3-pid>; rm -rf data3
bin/kafka-storage.sh format --cluster-id "$CLUSTER_ID" --config node3.properties --no-initial-controllers
bin/kafka-server-start.sh node3.properties
The new disk gets a new directory ID, so the quorum sees two different node 3s: the dead voter and a new observer that has caught up.
NodeId DirectoryId LogEndOffset Lag LastFetchTimestamp LastCaughtUpTimestamp Status
2 2KZpfWMmQkSqiKkmV8_HPQ 413 0 1796358788891 1796358788891 Leader
1 yZGOxtMPQ6mFf7lsgF8T9A 413 0 1796358788579 1796358788579 Follower
3 FAOpWsRAQmuvmVrXWMNeyA 310 103 1796358770064 1796358769568 Follower
3 RqnHshe9Qjz4nFCBy6BZgw 413 0 1796358788579 1796358788579 Observer
Swap the voter: remove the old directory ID, then add the new node using its own config file:
bin/kafka-metadata-quorum.sh --bootstrap-controller localhost:19093 \
remove-controller --controller-id 3 --controller-directory-id FAOpWsRAQmuvmVrXWMNeyA
bin/kafka-metadata-quorum.sh --command-config node3.properties \
--bootstrap-controller localhost:19093 add-controller
Removed KRaft controller 3 with directory id FAOpWsRAQmuvmVrXWMNeyA
Added controller 3 with directory id RqnHshe9Qjz4nFCBy6BZgw and endpoints: CONTROLLER://localhost:39093
Three seconds later the new node 3 was a voting follower at the same log end offset as the others. Its partition replicas re-replicated from the other two nodes, and 10 seconds after that --under-replicated-partitions printed nothing. The old row lingered as an “Observer” with lag 129 for a while; it’s the leader’s memory of a node that no longer exists and doesn’t affect the quorum.
This only works with a dynamic quorum (controller.quorum.bootstrap.servers at format time). With static controller.quorum.voters, membership can’t change at runtime: a replacement disk gets formatted with the same node ID and rejoins with an empty log, and you are relying on the other two voters being healthy while it catches up. That’s a good reason to format new clusters with the dynamic quorum.
Cross-region copy with MirrorMaker 2
For a region outage, mirror the important topics to a second cluster. A dedicated MirrorMaker 2 config (not run; needs two clusters):
# connect-mirror-maker.properties
clusters = primary, dr
primary.bootstrap.servers = broker-4.primary.example.com:9092
dr.bootstrap.servers = broker-1.dr.example.com:9092
primary->dr.enabled = true
primary->dr.topics = orders.*, payments.*
sync.group.offsets.enabled = true # translate consumer offsets so groups can fail over
replication.factor = 3
checkpoints.topic.replication.factor = 3
heartbeats.topic.replication.factor = 3
offset-syncs.topic.replication.factor = 3
offset.storage.replication.factor = 3
status.storage.replication.factor = 3
config.storage.replication.factor = 3
bin/connect-mirror-maker.sh connect-mirror-maker.properties
Mirroring is asynchronous, so a failover loses whatever hadn’t been copied yet. With the default replication policy, topics on the DR side are prefixed (primary.orders), and consumers have to be pointed at those names when they fail over.
Docker Compose: three controllers and three brokers
This runs a KRaft cluster with dedicated controllers on one Docker host using the official apache/kafka image. One host is one failure domain, so this is for staging, CI and failure drills, not production. I ran it with Docker 26.1.5 and Compose 2.40.3:
x-controller: &controller
image: apache/kafka:4.4.0
restart: unless-stopped
environment: &controller-env
KAFKA_PROCESS_ROLES: controller
KAFKA_LISTENERS: CONTROLLER://:9093
KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: CONTROLLER:PLAINTEXT
KAFKA_CONTROLLER_QUORUM_VOTERS: 1@controller-1:9093,2@controller-2:9093,3@controller-3:9093
CLUSTER_ID: 4L6g3nShT-eMCtK--X86sw
KAFKA_LOG_DIRS: /var/lib/kafka/data # image default is /tmp/kraft-combined-logs, outside the volume
# Topic-creation defaults are applied by the active controller in KRaft,
# so they must be set here, not only on the brokers.
KAFKA_DEFAULT_REPLICATION_FACTOR: 3
KAFKA_NUM_PARTITIONS: 6
KAFKA_MIN_INSYNC_REPLICAS: 2
KAFKA_HEAP_OPTS: -Xmx512m -Xms512m
x-broker: &broker
image: apache/kafka:4.4.0
restart: unless-stopped
depends_on: [controller-1, controller-2, controller-3]
environment: &broker-env
KAFKA_PROCESS_ROLES: broker
KAFKA_LISTENERS: INTERNAL://:19092,EXTERNAL://:9092
KAFKA_INTER_BROKER_LISTENER_NAME: INTERNAL
KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: CONTROLLER:PLAINTEXT,INTERNAL:PLAINTEXT,EXTERNAL:PLAINTEXT
KAFKA_CONTROLLER_QUORUM_VOTERS: 1@controller-1:9093,2@controller-2:9093,3@controller-3:9093
CLUSTER_ID: 4L6g3nShT-eMCtK--X86sw
KAFKA_LOG_DIRS: /var/lib/kafka/data
KAFKA_DEFAULT_REPLICATION_FACTOR: 3
KAFKA_MIN_INSYNC_REPLICAS: 2
KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 3
KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 3
KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 2
KAFKA_AUTO_CREATE_TOPICS_ENABLE: "false"
KAFKA_HEAP_OPTS: -Xmx1g -Xms1g
services:
controller-1:
<<: *controller
environment: { <<: *controller-env, KAFKA_NODE_ID: 1 }
volumes: [controller-1:/var/lib/kafka/data]
controller-2:
<<: *controller
environment: { <<: *controller-env, KAFKA_NODE_ID: 2 }
volumes: [controller-2:/var/lib/kafka/data]
controller-3:
<<: *controller
environment: { <<: *controller-env, KAFKA_NODE_ID: 3 }
volumes: [controller-3:/var/lib/kafka/data]
broker-1:
<<: *broker
ports: ["29092:9092"]
environment:
<<: *broker-env
KAFKA_NODE_ID: 4
KAFKA_ADVERTISED_LISTENERS: INTERNAL://broker-1:19092,EXTERNAL://localhost:29092
volumes: [broker-1:/var/lib/kafka/data]
broker-2:
<<: *broker
ports: ["39092:9092"]
environment:
<<: *broker-env
KAFKA_NODE_ID: 5
KAFKA_ADVERTISED_LISTENERS: INTERNAL://broker-2:19092,EXTERNAL://localhost:39092
volumes: [broker-2:/var/lib/kafka/data]
broker-3:
<<: *broker
ports: ["49092:9092"]
environment:
<<: *broker-env
KAFKA_NODE_ID: 6
KAFKA_ADVERTISED_LISTENERS: INTERNAL://broker-3:19092,EXTERNAL://localhost:49092
volumes: [broker-3:/var/lib/kafka/data]
volumes:
controller-1:
controller-2:
controller-3:
broker-1:
broker-2:
broker-3:
The image’s start script formats storage itself on first start using CLUSTER_ID (and skips it when the directory is already formatted). I used the static KAFKA_CONTROLLER_QUORUM_VOTERS form because the image handles it with no extra flags; I didn’t try the dynamic quorum with this image. Generate your own ID with kafka-storage.sh random-uuid.
Both comments in the controller block come from mistakes I made writing this file. Without the controller-side defaults, topics came out with replication factor 1 (shown in the configuration section above). Without KAFKA_LOG_DIRS, the data went to /tmp/kraft-combined-logs inside the container, the named volumes stayed empty, and after docker compose up -d recreated the controllers they formatted a brand-new metadata log with the same cluster ID. The brokers still held the old metadata, every broker heartbeat failed with NotControllerException: No controller appears to be active, and kafka-topics.sh --create hung until it timed out. With both fixes (run):
$ bin/kafka-metadata-quorum.sh --bootstrap-server localhost:29092 describe --replication
NodeId DirectoryId LogEndOffset Lag LastFetchTimestamp LastCaughtUpTimestamp Status
2 AAAAAAAAAAAAAAAAAAAAAA 73 0 1796358943691 1796358943691 Leader
1 AAAAAAAAAAAAAAAAAAAAAA 73 0 1796358943275 1796358943275 Follower
3 AAAAAAAAAAAAAAAAAAAAAA 73 0 1796358943274 1796358943274 Follower
4 Kv4BH0G5yqeiJNPB8tZQnw 73 0 1796358943273 1796358943273 Observer
5 satW75SVJtfJVQc3zaRAgg 73 0 1796358943274 1796358943274 Observer
6 M0eEbG1x4aEIlo9evxtefw 73 0 1796358943275 1796358943275 Observer
$ bin/kafka-topics.sh --bootstrap-server localhost:29092 --create --topic payments
Created topic payments.
Topic: payments TopicId: _B0_uLyARt2uCSBCl0dU3g PartitionCount: 6 ReplicationFactor: 3 Configs: min.insync.replicas=2
The all-A directory IDs are what a static quorum looks like: voters are identified by node ID only. I then wrote 500 records, ran docker compose up -d --force-recreate, and the topic still held 500 records; with broker-3 stopped, another 500 acks=all records went in (1,000 total).
Kubernetes with Strimzi
On Kubernetes, use an operator rather than a hand-written StatefulSet. Kafka needs ordered rolling restarts that wait for under-replicated partitions to clear, per-node advertised addresses, and certificate rotation, and a plain StatefulSet does none of that. The ZooKeeper-era StatefulSet in older guides also took KAFKA_BROKER_ID from the pod name, which isn’t a number.
Strimzi is the common open-source choice. Since Strimzi 1.0 it supports only KRaft and only the kafka.strimzi.io/v1 API, and node roles come from KafkaNodePool resources. Strimzi 1.3.1 (November 2026) supports up to Kafka 4.3.2, so on Strimzi you run what the operator supports, not the newest Apache release. The manifest below follows the Strimzi 1.3 documentation; I haven’t applied it to a cluster:
apiVersion: kafka.strimzi.io/v1
kind: KafkaNodePool
metadata:
name: controller
labels:
strimzi.io/cluster: prod
spec:
replicas: 3
roles: [controller]
resources:
requests: { cpu: "1", memory: 4Gi }
limits: { memory: 4Gi }
storage:
type: jbod
volumes:
- { id: 0, type: persistent-claim, size: 50Gi, class: fast-ssd, kraftMetadata: shared, deleteClaim: false }
---
apiVersion: kafka.strimzi.io/v1
kind: KafkaNodePool
metadata:
name: broker
labels:
strimzi.io/cluster: prod
spec:
replicas: 3
roles: [broker]
resources:
requests: { cpu: "4", memory: 32Gi }
limits: { memory: 32Gi }
jvmOptions:
-Xms: 6g
-Xmx: 6g
storage:
type: jbod
volumes:
- { id: 0, type: persistent-claim, size: 2Ti, class: fast-ssd, kraftMetadata: shared, deleteClaim: false }
---
apiVersion: kafka.strimzi.io/v1
kind: Kafka
metadata:
name: prod
spec:
kafka:
version: 4.3.2
rack:
topologyKey: topology.kubernetes.io/zone
listeners:
- name: tls
port: 9093
type: internal
tls: true
authentication:
type: scram-sha-512
authorization:
type: simple # StandardAuthorizer under the hood in KRaft
config:
default.replication.factor: 3
min.insync.replicas: 2
offsets.topic.replication.factor: 3
transaction.state.log.replication.factor: 3
transaction.state.log.min.isr: 2
auto.create.topics.enable: false
entityOperator:
topicOperator: {}
userOperator: {}
rack.topologyKey does the zone spreading described at the top. deleteClaim: false keeps the volumes if someone deletes the node pool by mistake. Create topics as KafkaTopic resources with replicas: 3 written out, so the controller-default trap from the configuration section can’t bite.
Troubleshooting
Consumer lag climbing
bin/kafka-consumer-groups.sh --bootstrap-server broker-4:9092 --describe --group analytics-group
Look at the LAG column per partition before changing anything. Lag on one or two partitions points to a hot key or one slow consumer; lag on all of them means the group is too slow overall, and then more consumers help only up to the partition count. The lag lesson goes through each case.
Broker heap pressure
jstat -gcutil <kafka-pid> 1s
A 6 GB heap that keeps filling up usually comes from too many partitions per broker or very large max.request.size / fetch sizes, not from message volume; message data lives in the page cache, not the heap. Fix the cause before raising the heap.
Disk filling up
See which broker is using the space (run):
bin/kafka-log-dirs.sh --bootstrap-server localhost:19092 --describe 2>/dev/null | grep '^{' \
| jq -r '.brokers[] | "broker \(.broker): \([.logDirs[].partitions[].size] | add) bytes"'
broker 1: 8174 bytes
broker 2: 8174 bytes
broker 3: 8174 bytes
The grep '^{' matters: the tool prints two status lines before the JSON, and jq fails on them. If one topic dominates, lower its retention.ms or retention.bytes with kafka-configs.sh --alter; Kafka deletes whole segments past the limit, so the space comes back after the next retention check (log.retention.check.interval.ms, 5 minutes by default), not instantly. Don’t delete segment files by hand.
Production checklist
Before go-live:
- Three dedicated controllers in three zones;
describe --statusshows 3 voters and one leader - Brokers have
broker.rackset; RF 3 andmin.insync.replicas=2set on brokers and controllers -
auto.create.topics.enable=false,unclean.leader.election.enable=false - TLS on every listener including
CONTROLLER; SASL or mTLS for clients;StandardAuthorizerwith per-application ACLs -
vm.max_map_countandnofileraised; heap 6 GB, the rest left to page cache - JMX exporter on every node; alerts on active controller count, offline, under-min-ISR and under-replicated partitions, disk, consumer lag
- Nightly metadata export (or topics and ACLs as code) and a MirrorMaker 2 plan if region loss is in scope
Rehearsed at least once:
- Kill the active controller and time the election
- Stop one broker under load, then two, and confirm producers see
NOT_ENOUGH_REPLICASrather than silent data loss - Replace a controller with a wiped disk using
remove-controller/add-controller - Rolling restart of all brokers with producers and consumers running
Where to go next
The production lesson in the free Kafka course adds capacity planning and an incident drill on a local cluster. For TLS certificates, SCRAM users and quotas, see the security lesson. If you want the controller and ISR mechanics behind this guide, read Kafka architecture explained.