Bookmarks
ReferenceData & AIBackendVerified

Kafka

Apache Kafka is a distributed event streaming platform for exchanging data. The reference covers: KRaft, topics, producers, consumers, Connect, Streams.

checked 7 Nov · next check 14 Nov · 83 min read

Sections
14
Reading
83 min
Current version
4.4.0
Written from
kafka.apache.org/documentation

Check status of the reference

Verified 7 Nov · next check 14 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What Kafka is and how it works

Apache Kafka is a distributed event streaming platform: producers publish events to topics, Kafka stores them on disk, and consumers read them when they are ready. It suits exchanging events between services, collecting logs and metrics, and stream processing.

Kafka is a distributed system of servers and clients that talk over TCP. Some of the servers are brokers: together they form the event store. Clients are applications that write and read events. Producers and consumers know nothing about each other: a producer does not wait for a consumer.

An event (event, also record and message in the documentation) records the fact that something happened. An event has a key, a value, a timestamp and optional headers: the key “Alice”, the value “sent Bob 200 dollars”, the time of the payment.

How Kafka stores events

Events are gathered into topics — logical channels, similar to folders with files. A topic may have any number of consumers, and an event is not removed after reading: Kafka keeps it for a set time, say a week, and then discards it. So events can be re-read from any point.

Each topic is divided into partitions — “buckets” spread across different brokers. Events with the same key always land in the same partition, and ordering is guaranteed only within a partition. If event A and event B end up in different partitions, nobody promises the order in which they will be read.

The orders-0 partition is highlighted: events with one key always land in it.

The utilities that ship with Kafka do the same as client applications: create a topic, write events into it, read them back — a way to check the cluster before writing your own code:

bashin the Kafka distribution directory
bin/kafka-topics.sh --create \  --topic orders \  --partitions 3 \  --bootstrap-server localhost:9092bin/kafka-console-producer.sh \  --topic orders \  --bootstrap-server localhost:9092
bashin another terminal
bin/kafka-console-consumer.sh \  --topic orders \  --from-beginning \  --bootstrap-server localhost:9092

The --from-beginning flag reads partitions from the very beginning, not from the end. By setting --partitions 3 you set the number of topic partitions. See the section “Installation and first run” for installing and starting a broker.

Who works with Kafka and through what

Clients talk to brokers over the Kafka network protocol. Clients exist for Java and Scala, Go, Python, C/C++ and other languages. The core of Kafka is six APIs:

APIWhat it is for
ProducerWrites a stream of events to one or more topics
ConsumerReads events from topics and processes them
Share ConsumerProcesses events cooperatively, from a share group
StreamsTurns streams from input topics into streams in output topics
ConnectConnects Kafka to external systems: source and sink connectors
AdminManages and inspects topics, brokers and other cluster objects

Moving data from databases and files is usually not written by hand: Kafka Connect offers hundreds of ready connectors. For example, a PostgreSQL connector can pass every change of a table into Kafka. Moving changes this way is called change data capture (CDC).

Where Kafka fits and where it does not

Kafka is chosen when events flow between services as a stream, when every event may be read several times, and when losing an event is not an option. Typical cases from the documentation: replacing a classic message broker, tracking user actions on a website, collecting metrics and logs, multi-stage stream processing, event sourcing, and an external commit log for a distributed system.

Kafka is not needed when a synchronous request–response is enough for the services: an API call is simpler and clearer. It is also not needed at small loads, when a queue in a database or Redis Streams is enough: a cluster for a dozen events per minute is an extra system to operate.

How it differs from Redis Streams

Redis Streams is a Redis data type similar to an event log: records are appended and read, consumer groups distribute records among clients. The purpose is the same, the design is not: the comparison by key traits is in the table.

TraitKafkaRedis Streams
Where events are storedon the brokers’ disk, volume limited by time and policyin the memory of a Redis node, old records are trimmed by MAXLEN or XTRIM
Write scalingtopic partitions are spread across brokersone Redis key; distribution is manual, by keys or via Redis Cluster
Consumer groupspartitions are assigned to group membersall read one log: whoever is ready gets the record
Orderguaranteed within a partitionguaranteed within a single stream
Retentionconfigured per topic: hours, days, yearsby default unlimited — until you trim it
EcosystemConnect, Streams, hundreds of clients and ready connectorsRedis clients and the XADD, XREAD, XREADGROUP commands

Choose Kafka when events are the main data stream between services, the volumes grow, and history is needed for a long time with guaranteed order within a partition. Redis Streams is enough when the stream is small, the data fits in Redis memory, and a separate cluster is not wanted.

What to know in advance

  • Containers and Docker Compose — the Docker reference: a local Kafka cluster is set up in containers.
  • Java basics — client examples in the documentation are written in Java and Scala.
  • Command line and bash — the Bash reference: Kafka utilities are run from the terminal.

Section sources

the section is written from these pages

Cheat sheet

This section gathers the Kafka commands you need every day: topics, producing and reading in the terminal, consumer groups, dynamic configuration and cluster checks. Replace the names in the examples (orders, billing) with your own. The flags and pitfalls of each command are covered in its own section of the reference.

The commands are run with scripts from the bin/ directory of your Kafka installation and connect to the cluster via --bootstrap-server localhost:9092 — replace the address and port with your own. Run without arguments, a tool prints the full list of its options.

Topics

TaskCommand
Create a topickafka-topics.sh --bootstrap-server localhost:9092 --create --topic orders --partitions 6 --replication-factor 3
Create with a retention settingkafka-topics.sh --bootstrap-server localhost:9092 --create --topic orders --partitions 6 --replication-factor 3 --config retention.ms=604800000
List topicskafka-topics.sh --bootstrap-server localhost:9092 --list
Partition detailskafka-topics.sh --bootstrap-server localhost:9092 --describe --topic orders
Find under-replicated partitionskafka-topics.sh --bootstrap-server localhost:9092 --describe --under-replicated-partitions
Add partitionskafka-topics.sh --bootstrap-server localhost:9092 --alter --topic orders --partitions 12

The partition count cannot be reduced — only recreate the topic and move the data over. Adding partitions changes key-based routing: after the partition count grows, messages with the same key may end up in a different partition.

Producing and consuming

TaskCommand
Send lines from the terminalkafka-console-producer.sh --bootstrap-server localhost:9092 --topic orders
Send key and value pairskafka-console-producer.sh --bootstrap-server localhost:9092 --topic orders --reader-property parse.key=true
Read from the very beginningkafka-console-consumer.sh --bootstrap-server localhost:9092 --topic orders --from-beginning
Read with keyskafka-console-consumer.sh --bootstrap-server localhost:9092 --topic orders --formatter-property print.key=true
Read as a consumer groupkafka-console-consumer.sh --bootstrap-server localhost:9092 --topic orders --group billing --from-beginning
Limit the number of messageskafka-console-consumer.sh --bootstrap-server localhost:9092 --topic orders --from-beginning --max-messages 5
Last offset of each partitionkafka-get-offsets.sh --bootstrap-server localhost:9092 --topic orders

Without --group the consumer reads on its own: you start it and fresh messages arrive, you stop it and the position is lost. With --group offsets are stored under the group name, and after a restart reading resumes from the saved position.

Consumer groups

TaskCommand
List groupskafka-consumer-groups.sh --bootstrap-server localhost:9092 --list
Consumer lag per partitionkafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group billing
Group statekafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group billing --state
Group membershipkafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group billing --members
Dry run: what an offset reset would changekafka-consumer-groups.sh --bootstrap-server localhost:9092 --reset-offsets --group billing --topic orders --to-earliest --dry-run
Reset to a point in timekafka-consumer-groups.sh --bootstrap-server localhost:9092 --reset-offsets --group billing --topic orders --to-datetime 2026-11-05T00:00:00.000 --dry-run

An offset reset always goes through --dry-run first: the command prints a plan and changes nothing. The reset itself is performed by --execute, and the plan can be saved to CSV with the --export flag. The group must have no active members for this.

Configuration

TaskCommand
Show topic configurationkafka-configs.sh --bootstrap-server localhost:9092 --describe --entity-type topics --entity-name orders
Override a settingkafka-configs.sh --bootstrap-server localhost:9092 --alter --entity-type topics --entity-name orders --add-config retention.ms=86400000
Reset a setting to its defaultkafka-configs.sh --bootstrap-server localhost:9092 --alter --entity-type topics --entity-name orders --delete-config retention.ms
Quota for a clientkafka-configs.sh --bootstrap-server localhost:9092 --alter --add-config consumer_byte_rate=1048576 --entity-type clients --entity-name clientA
Show broker configurationkafka-configs.sh --bootstrap-server localhost:9092 --describe --entity-type brokers

Only dynamic settings are changed through --alter; the full list of topic values — retention.ms, cleanup.policy, min.insync.replicas — is given in the “Topics, partitions and retention” section.

Cluster

TaskCommand
State of the metadata quorumkafka-metadata-quorum.sh --bootstrap-server localhost:9092 describe --status
Lag of the quorum followerskafka-metadata-quorum.sh --bootstrap-server localhost:9092 describe --replication
Supported API versionskafka-cluster.sh api-versions --bootstrap-server localhost:9092
Cluster IDkafka-cluster.sh cluster-id --bootstrap-server localhost:9092
Return leadership to the preferred replicaskafka-leader-election.sh --bootstrap-server localhost:9092 --election-type preferred --all-topic-partitions
Records in a topic segmentkafka-dump-log.sh --files /tmp/kraft-combined-logs/orders-0/00000000000000000000.log --print-data-log

Dangerous commands

TaskCommand
Delete a topickafka-topics.sh --bootstrap-server localhost:9092 --delete --topic orders
Reset offsets to the beginningkafka-consumer-groups.sh --bootstrap-server localhost:9092 --reset-offsets --group billing --topic orders --to-earliest --execute
Delete a group’s offsetskafka-consumer-groups.sh --bootstrap-server localhost:9092 --delete --group old-jobs
Prepare storage for a new nodekafka-storage.sh format --cluster-id $(kafka-storage.sh random-uuid) --config config/server.properties

Section sources

the section is written from these pages

Architecture: brokers and KRaft

A Kafka cluster is brokers, which store topic partitions, and KRaft controllers, which keep the cluster metadata in a shared metadata log. An event reaches a partition’s log through the partition leader and becomes visible to consumers once the in-sync replicas (ISR) have acknowledged it.

The role of each server is set in process.roles: broker, controller, or both at once. A broker takes records in and serves them to consumers; a controller takes no part in the event flow and is responsible only for metadata: the list of nodes, topics and partitions, and their configuration. A server with both roles is called combined: it saves resources in development, but its controller is not isolated from the brokers, and the two cannot be scaled separately — in production the roles are kept apart.

One controller is active and two are on standby; partition leaders are spread across the brokers.
RoleWhat it storesWhere it fits
brokertopic partitionsproduction
controllercluster metadataproduction
broker,controllerpartitions and metadatadevelopment and tests

The controller quorum

The controllers form a quorum and talk over the Raft protocol. One controller is active and leads the metadata log; the rest are a hot standby, ready to take over the active role. A production cluster runs 3 or 5 controllers: the quorum keeps working while a majority is alive, so three controllers survive one failure and five survive two. Controllers keep all the cluster metadata in memory and on disk; a typical cluster needs about 5 GB of memory and the same on disk.

The quorum type and the initial set of controllers are chosen when the storage is formatted. In a static quorum the controllers are listed in controller.quorum.voters; in a dynamic one the controller addresses are set in controller.quorum.bootstrap.servers, and the membership is changed on a running cluster with the bin/kafka-metadata-quorum.sh add-controller and remove-controller commands. A running cluster can be moved from a static quorum to a dynamic one from Kafka 4.1. Brokers and controllers use the same list to find the active controller.

propertiescontroller.properties
process.roles=controllernode.id=1listeners=CONTROLLER://c1.example.com:9093controller.quorum.bootstrap.servers=\  c1.example.com:9093,c2.example.com:9093,c3.example.com:9093controller.listener.names=CONTROLLER

A partition on disk

A partition lives on the broker’s disk as a directory inside log.dirs, for example my-topic-0. The log consists of segments — files with records; only the active segment takes writes. Each segment is named after the offset of its first record: 00000000000000000000.log, with the offset (.index) and time (.timeindex) indexes next to it. When a segment reaches its limit (1 GiB by default, log.segment.bytes), the broker opens the next one. Index entries are added about every 4096 bytes (index.interval.bytes), so a position can be found by offset without scanning the whole segment.

bashon the server
bin/kafka-dump-log.sh \  --files /var/kafka-logs/my-topic-0/00000000000000000000.log

Appending to the end and reading sequentially is the most predictable pattern of disk use, and the broker does not keep data on its heap: records go straight into the kernel’s page cache; from there the kernel flushes them to disk and serves them to consumers. Recent records are read from the cache, older ones from disk; against loss on a node failure the data is protected by replication, not by forcing a flush of every record. Closed segments can be moved to external storage, such as S3 — this is tiered storage; by default it is disabled (remote.log.storage.system.enable).

What happens on a write

A write is acknowledged by the partition leader and its in-sync replicas (ISR) — replicas that have not fallen behind the leader. The path of an event from producer to consumer:

  1. The producer asks any broker which server leads the partition it needs, and sends a batch of events to that server.
  2. The leader appends the batch to the end of its partition’s log.
  3. Followers pull records from the leader the same way consumers do, and append them to their own logs.
  4. Once every replica in the ISR has applied the record, the boundary of acknowledged records — the high watermark — moves up.
  5. Consumers see records only up to the high watermark; the unacknowledged tail of the log may disappear when the leader changes.

Whether the producer waits for an acknowledgement, and how many replicas have to sign it, is set by acks — see the sections “Producers” and “Replication and fault tolerance”.

Section sources

the section is written from these pages

Installation and first run

The fastest official way to run Kafka locally is the apache/kafka Docker image, started with a single command. The second way is an archive from the project website, run in KRaft mode. Check the installation with the console tools: create a topic, write an event and read it back.

Docker

Apache Kafka publishes the official apache/kafka image on Docker Hub. Inside is Kafka in KRaft mode configured for a single node: the broker and the controller, which manages cluster coordination, run in one process. The command starts a container and publishes the client port to the host:

bashon the host
docker run -p 9092:9092 --name broker apache/kafka:4.4.0

The container runs in the foreground: logs go to the terminal, and Ctrl-C stops it. The command line scripts are included in the image, so you can check the installation right inside the container:

bashsecond terminal
docker exec --workdir /opt/kafka/bin/ -it broker sh

There is also an experimental GraalVM image, apache/kafka-native: it starts faster and uses less memory, but it is intended only for local development and testing, and is not recommended for production.

Linux

Download an archive with the current release from the project downloads page — the number in the URL changes with every release; a signature and a sha512 checksum sit alongside, so verify the file before running it. Running Kafka needs Java 17 or newer: Java 17, 21 and 25 are fully supported, and the newest long-term support (LTS) release is recommended.

bashon the host
wget https://downloads.apache.org/kafka/4.4.0/kafka_2.13-4.4.0.tgztar -xzf kafka_2.13-4.4.0.tgzcd kafka_2.13-4.4.0

Before the first run, format the storage: take the cluster ID from random-uuid and write it into the data directory together with the service files. Formatting is done once, before the very first run.

bash
KAFKA_CLUSTER_ID="$(bin/kafka-storage.sh random-uuid)"bin/kafka-storage.sh format --standalone \  -t $KAFKA_CLUSTER_ID \  -c config/server.properties

The --standalone flag describes a single node: it is a broker and a controller at once — the roles are covered in detail in the “Architecture: brokers and KRaft” section. Start the server — it runs until you press Ctrl-C:

bashon the host
bin/kafka-server-start.sh config/server.properties

macOS and Windows

On macOS and Windows, Kafka runs from the same Docker image: install Docker Desktop and run the command from the “Docker” section — from then on everything is the same, because inside the container Kafka runs on Linux.

server.properties settings

The config/server.properties file describes the node. In the archive it is already configured for a single node, so the first run needs no edits. The key settings come in handy when the node is not the first in the cluster or the ports are taken:

SettingWhat it controlsValue from the archive
process.rolesThe roles of the process: broker, controller or both at once — one processbroker,controller
node.idThe node number; required in KRaft mode, the process roles are tied to it1
listenersThe addresses the node listens on, in the name://host:port format: the client listener and the controller’s service listenerPLAINTEXT://:9092,CONTROLLER://:9093
advertised.listenersThe addresses the broker advertises to clients and other brokers: clients connect using themPLAINTEXT://localhost:9092,CONTROLLER://localhost:9093
log.dirsThe directories where event files are stored/tmp/kraft-combined-logs

Check

In a new terminal, create a topic — the channel that events are written to:

bashnew terminal
bin/kafka-topics.sh --create --topic quickstart-events \  --bootstrap-server localhost:9092

Write a couple of events with the console producer — each line you enter becomes a separate event. The producer waits for input at the > prompt; Ctrl-C exits.

bashnew terminal
bin/kafka-console-producer.sh --topic quickstart-events \  --bootstrap-server localhost:9092
textexample input
This is my first eventThis is my second event

In a new terminal, read what was written with the console consumer:

bashnew terminal
bin/kafka-console-consumer.sh --topic quickstart-events \  --from-beginning --bootstrap-server localhost:9092
textexample output
This is my first eventThis is my second event

The consumer prints events from the beginning of the log — that is what the --from-beginning flag does — and keeps waiting for new ones. Stop it with Ctrl-C. Run it again: you will see the same events, because Kafka does not remove them after reading — they are kept for a set time.

When you are done, stop the producer, the consumer and the server with Ctrl-C. To wipe the local environment clean, delete the data directory from log.dirs — /tmp/kraft-combined-logs.

Section sources

the section is written from these pages

Topics, partitions and retention

A topic is a named channel that producers write events to, and Kafka keeps them on disk for a set time. A topic is split into partitions: the event key determines the partition, and ordering is guaranteed only within it. Partitions and retention determine read parallelism and how much data sits on disk.

Partitions and event ordering

A partition is an ordered log of events, and the number of an event in it is called the offset. The reader chooses its own position in the log and can re-read events.

By default, a producer sends events with the same key to the same partition: the partition is chosen by hashing the key. Events without a key are spread across partitions to balance the load.

Ordering is guaranteed only within a partition: events with the key user=17 are read in the order the producer wrote them. There is no ordering across partitions. Splitting by keys also helps on the reading side: all events of one user are handled by a single consumer.

The number of partitions is the main scaling parameter of a topic. A partition lives entirely on a single broker, and within a consumer group each partition is assigned to one consumer. The number of partitions therefore also limits how many consumers can read the topic at the same time.

How many partitions to create

Write throughput of a topic is the combined throughput of all its partitions, and each partition is bound to the disk of a single broker. For a typical workload, start with a small number — say 6–12 partitions — and add more as the load grows. Partitions take up broker memory, and when a broker fails, the leaders of all its partitions have to be re-elected.

The replication factor is the number of copies of each partition: how many brokers keep its log. A single copy means the data is lost when that broker’s disk fails; three copies survive the failure of two brokers. Production topics get 3, drafts get by with 1.

bashin the Kafka distribution directory
bin/kafka-topics.sh --create \  --topic orders \  --partitions 6 \  --replication-factor 3 \  --bootstrap-server localhost:9092bin/kafka-topics.sh --describe \  --topic orders \  --bootstrap-server localhost:9092

The output of --describe shows the partitions, their leaders and the in-sync replicas (ISR) — copies that are not lagging behind the leader. For more on replication, see the section “Replication and fault tolerance”.

How Kafka stores and deletes events

A partition log sits on disk as segments — files sized by segment.bytes (1 GiB by default). A new segment opens when the active one is full or has aged past segment.ms; writes always go to the last segment. Old events are deleted whole segments at a time: until a segment has aged out entirely, Kafka leaves it alone.

The deletion policy (cleanup.policy=delete) is the default. Segments are discarded once events age past retention.ms (7 days by default) or the partition log grows past retention.bytes (unlimited by default). The two limits work independently: whichever is hit first takes effect. A value of -1 removes the limit.

Topic settingWhat it doesDefault
retention.msHow long to keep events before a segment is discarded604800000 (7 days)
retention.bytesMaximum size of a single partition’s log-1 (no limit)
cleanup.policyCleanup policy: delete, compact or delete,compactdelete
min.insync.replicasMinimum number of in-sync replicas for writes with acks=all1
max.message.bytesLargest size of an event batch in a partition1048588
segment.bytesSize of a partition log segment1073741824 (1 GiB)
segment.msAge after which the active segment is closed604800000 (7 days)

Log compaction

The compact policy (cleanup.policy=compact) keeps not all events but the latest value of each key. Older events with the same key are removed, and the log becomes a snapshot of the current values. This is how, for example, changes to a database table are stored: reading the log from the beginning yields the current state for each key.

Compaction runs as a background process, the log cleaner: it rewrites segments, keeping the last event of each key, and does not block reads or writes. Offsets do not change: if an event has been removed, its offset is skipped when reading.

A record with a key and a null value (a tombstone) deletes the key: it erases all earlier events for the key and then disappears itself — after delete.retention.ms by default, one day.

Compaction removes old events of keys but does not renumber offsets.

Both policies can be enabled together: cleanup.policy=delete,compact — old segments are then discarded by retention.ms and retention.bytes, and the remaining ones are compacted. That way the log does not grow indefinitely even with rare updates of rarely used keys.

Creating and modifying topics

By default, the broker creates a topic itself on the first write to a non-existent one: auto.create.topics.enable is enabled. In a development environment this saves a step. In production it leads to junk topics: a typo in a name creates a topic with default settings (num.partitions=1 and replication factor 1). Production clusters therefore disable auto-creation and create topics with the kafka-topics.sh --create command and explicit settings.

The number of partitions is increased with the same command plus --alter. Topic settings are changed and viewed with kafka-configs.sh:

bashin the Kafka distribution directory
bin/kafka-topics.sh --alter \  --topic orders --partitions 12 \  --bootstrap-server localhost:9092bin/kafka-configs.sh --alter \  --entity-type topics --entity-name orders \  --add-config retention.ms=259200000 \  --bootstrap-server localhost:9092
bashwhich settings are overridden
bin/kafka-configs.sh --describe \  --entity-type topics --entity-name orders \  --bootstrap-server localhost:9092

Deleting a topic is kafka-topics.sh --delete: brokers mark the topic as deleted and erase its data on disk in the background; the delete.topic.enable option controls this. After deletion, a topic with the same name can be created again, but the old data cannot be recovered.

Section sources

the section is written from these pages

Producers

A producer is a client that sends events to a topic. The send() method puts the event into a buffer and returns immediately; a background thread gathers events into batches and passes them to the broker. acks, linger.ms and compression set how reliable and how fast writes are.

send() is asynchronous: the event goes into a buffer, and the method immediately returns a Future with metadata — the partition, offset and timestamp. A background thread gathers events into batches and sends them to the broker; the result arrives in the Future or in a callback. Calling get() on the Future blocks the thread until the write is acknowledged. The producer is thread-safe: keep one instance per application — that is faster than an instance per thread.

Sending an event from code

The dependency for the Java client and a minimal producer:

xmlpom.xml
<dependency>  <groupId>org.apache.kafka</groupId>  <artifactId>kafka-clients</artifactId>  <version>4.4.0</version></dependency>
javaJava
Properties props = new Properties();props.put("bootstrap.servers", "localhost:9092");props.put("key.serializer",    "org.apache.kafka.common.serialization.StringSerializer");props.put("value.serializer",    "org.apache.kafka.common.serialization.StringSerializer"); try (Producer<String, String> producer = new KafkaProducer<>(props)) {    producer.send(new ProducerRecord<>("orders", "user-17", "created"),        (metadata, error) -> {            if (error != null) {                System.err.println("delivery failed: " + error);            }        });}

Serializers turn the key and value of an event into bytes: StringSerializer will do for strings, ByteArraySerializer for bytes. The callback runs after the broker acknowledges the write: it receives the record metadata or an error. try-with-resources closes the producer, and close() before exit waits for everything still in the buffer to be sent.

The console producer sends to the topic whatever you type in the terminal:

bashin the Kafka distribution directory
bin/kafka-console-producer.sh \  --topic orders \  --bootstrap-server localhost:9092

Where an event goes

The producer chooses the partition for an event. With a key, the partition is computed from the hash of the key: all events with the same key land in one partition and keep their order relative to each other (see the section “Topics, partitions and retention”). You can set the partition explicitly in ProducerRecord, and plug in your own algorithm as a class in partitioner.class by implementing the Partitioner interface.

Without a key, the sticky partitioner comes into play: events go to one partition until batch.size bytes have accumulated for it, then the partition changes. This keeps batches dense, while events spread across all partitions over time.

Three levels of acknowledgement in acks

The acks setting defines whose acknowledgement the producer waits for before it considers a send successful. The higher the level, the more reliable and the slower the writes.

ValueWhat it guaranteesWhen to choose it
0The producer does not wait for the broker’s response; the offset in the response is always -1, and retries do not workMetrics and logs you can afford to lose
1The leader has written the event to its own log without waiting for replicas; the event is lost if the leader fails before replicationOrdinary writes, when losing a single event is acceptable
allAll in-sync replicas (ISR) have acknowledged the write; the event is not lost as long as at least one replica is alivePayments, orders and anything you cannot afford to lose

all is the most reliable level, and the one the idempotent producer needs. Together with it, min.insync.replicas=2 is set on the topic (see the section “Replication and fault tolerance”): with acks=all, at least as many in-sync replicas as this setting specifies must acknowledge the event. If there are fewer in-sync replicas, the broker replies with a NotEnoughReplicasException error and the write does not go through — instead of writing to the only copy.

Idempotence and ordering

The idempotent producer has been enabled by default since Kafka 3.0. The broker assigns the producer an identifier and discards duplicate writes by sequence number, so an automatic retry does not create duplicates in the log. This requires acks=all, retries greater than zero and max.in.flight.requests.per.connection no greater than 5; with idempotence enabled, the order of records in a partition holds for any valid value of max.in.flight.

By default retries equals the maximum integer value, and it is delivery.timeout.ms that bounds retries — the total time from send() to the success or error report (2 minutes by default). The documentation advises not setting retries at all and controlling retries through delivery.timeout.ms. Idempotence protects against retries made by the client itself within one session: resending at the application level after an error will not remove duplicates.

If idempotence is disabled and max.in.flight.requests.per.connection is greater than 1, ordering breaks on retries: a retried batch can land in the log after the batch that follows it.

Batches, buffer and compression

A batch is a set of events for one partition that the background thread sends in a single request. A batch goes out once batch.size (16384 bytes by default) has accumulated or linger.ms has elapsed (5 ms by default, since Kafka 4.0). Under load, batches form on their own; linger.ms adds density at a moderate event rate — at the cost of a delay of up to its value. Compression applies to the batch as a whole (compression.type), so the denser the batch, the better the compression.

Unsent events sit in the buffer.memory buffer (32 MiB by default). If the network or the broker cannot keep up, the buffer fills: send() blocks the thread until space is freed, but for no longer than max.block.ms (1 minute), after which it returns a BufferExhaustedException error.

SettingWhat it doesDefault
acksWhose acknowledgement to wait for: 0, 1 or allall
enable.idempotenceDeduplicates retries on the brokertrue
retriesNumber of retries, limited by delivery.timeout.ms2147483647
delivery.timeout.msTime allowed to deliver an event: waiting, retries, acknowledgement120000 (2 minutes)
max.in.flight.requests.per.connectionHow many unacknowledged requests to keep per connection5
linger.msHow long to wait before sending an incomplete batch5
batch.sizeSize of a batch for one partition, in bytes16384
compression.typeBatch compression: none, gzip, snappy, lz4, zstdnone
buffer.memoryMemory for unsent events, in bytes33554432 (32 MiB)
max.block.msHow long send() waits for buffer space and metadata60000
max.request.sizeMaximum size of a request carrying batches, in bytes1048576

A producer with transactional.id can write events to several partitions and topics atomically — the section “Delivery guarantees and transactions” covers this. How consumers read what has been written is described in the section “Consumers and consumer groups”.

Section sources

the section is written from these pages

Consumers and groups

A consumer reads events from a topic at its own pace and decides for itself where to start. A consumer group divides the topic’s partitions between its members: each partition goes to exactly one of them, so read scaling is limited by the number of partitions. The group keeps its read position in Kafka.

How a consumer reads a topic

The consumer pulls data from the leaders of its partitions on its own: the pace of reading stays under its control. In the request it names the position — the offset — and receives a portion of the log from that point; the position can be moved back to read the events again.

The Java client KafkaConsumer is the model for clients in other languages: subscription via subscribe(), key and value deserialisers, and a loop that fetches records with poll() and processes them one at a time:

javaJava client
Properties props = new Properties();props.setProperty("bootstrap.servers", "localhost:9092");props.setProperty("group.id", "billing");props.setProperty("auto.offset.reset", "earliest");props.setProperty("key.deserializer",    "org.apache.kafka.common.serialization.StringDeserializer");props.setProperty("value.deserializer",    "org.apache.kafka.common.serialization.StringDeserializer");KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);consumer.subscribe(Arrays.asList("orders"));while (true) {    ConsumerRecords<String, String> records =        consumer.poll(Duration.ofMillis(500));    for (ConsumerRecord<String, String> record : records) {        System.out.printf("%s = %s%n", record.key(), record.value());    }}

The console consumer does the same in the terminal. Without a group it reads “on its own”, and with the --group flag it works as a member of a group: on the next run it continues from the saved position. The console commands are gathered in the “Cheat sheet”.

bashthe console consumer as a member of a group
bin/kafka-console-consumer.sh \  --topic orders \  --group billing \  --bootstrap-server localhost:9092

Consumer groups

Members of a group with one group.id divide the partitions of the subscribed topics between them: at any moment each partition goes to exactly one of them. If there are more consumers than partitions, the extra ones sit idle. Different groups read the same topic independently: inside a group events are shared between the members like in a queue, while each group receives every event of the topic in full.

The membership of the group changes — and the partitions are divided anew; this is a rebalance: a member disconnected, a new one connected, or the topic gained more partitions. In the diagram two consumers read four partitions, two each; a third joining redivides them 2–1–1, and partition 3 moves to the new member.

Partition 3 is highlighted: it changed owner in the rebalance.

Offsets and committing the position

The saved position of the group is the committed offset: the number of the next event the group will read. Kafka stores offsets in an internal topic — one number per partition, so “confirming a record as processed” is cheap.

By default offsets are committed automatically: enable.auto.commit=true — a background task sends the position every auto.commit.interval.ms, once every 5 seconds. Manual mode is switched on with enable.auto.commit=false and a call to commitSync(), which waits for the broker’s acknowledgement, or commitAsync(), which does not — for example after writing the processed events to a database.

With no saved offset — a new group, or the data already removed by retention — the auto.offset.reset setting chooses the starting position: latest (the default) starts at the end of the log, earliest at the beginning, and none fails with an error. The by_duration:PT10M option steps 10 minutes back and protects against silently losing events when partitions are added — a case where latest skips records until the first poll of the new partition.

Rebalancing

The group monitors whether a member is alive by two timeouts. session.timeout.ms — a member whose heartbeats stay silent for longer is considered dead. max.poll.interval.ms — if two calls to poll() drift further apart, the member leaves the group on its own: processing has “hung”. max.poll.records caps the batch so that processing fits between the calls. If processing does take longer than the timeout, commitSync() fails with a CommitFailedException.

Static membership removes rebalances across restarts: set group.instance.id — a permanent identifier of the member, unique within the group. Restarting the process with the same identifier does not trigger a rebalance: the coordinator waits for the member to return within the session timeout.

The new rebalance protocol is production-ready from Kafka 4.0: it is switched on for the consumer with group.protocol=consumer. The broker, not the members, assigns partitions, and the rebalance is incremental, without stopping all the members, so it goes faster. The cluster sets the heartbeat interval and the session timeout — group.consumer.heartbeat.interval.ms and group.consumer.session.timeout.ms; the client-side session.timeout.ms, heartbeat.interval.ms and partition.assignment.strategy then have no effect. The broker chooses the distribution: uniform by default, replaceable via group.remote.assignor.

Consumer settings

SettingWhat it doesDefault
group.idthe name of the group under which the offsets are stored—
enable.auto.commitcommits the offset in the backgroundtrue
auto.commit.interval.msthe pause between auto-commits5000 (5 seconds)
auto.offset.resetwhere to start when there is no saved offsetlatest
max.poll.recordshow many records poll() returns500
max.poll.interval.msthe maximum between two calls to poll()300000 (5 minutes)
session.timeout.msthe liveness timeout of a member (classic)45000 (45 seconds)
group.protocolthe group protocol: classic or consumerclassic
group.instance.ida permanent identifier of the member—
isolation.levelread_committed hides incomplete transactionsread_uncommitted

Consumer lag and how to look at it

Lag is how far the group is behind the end of the log: the difference between the last offset of a partition and the committed position. kafka-consumer-groups.sh shows it per partition and per member:

bashin the Kafka distribution directory
bin/kafka-consumer-groups.sh --describe \  --group billing \  --bootstrap-server localhost:9092
textexample output
GROUP    TOPIC   PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAGbilling  orders  0          12              15              3billing  orders  1          12              12              0...

Steadily growing lag means the consumer cannot keep up: add members within the number of partitions, raise max.poll.records, or speed up the processing. For continuous monitoring use the metrics and dashboards from the Prometheus and Grafana reference; the offset reset from the “Cheat sheet” helps to re-read what has already been processed.

Share groups: a queue in Kafka

A share group is the second type of group, production-ready from Kafka 4.2: a partition is not pinned to a single member, and there may be more consumers than partitions. A record is handed out with a time-limited lock: while the lock holds, the record is unavailable to the other members of the group; by default the lock lives for 30 seconds — share.record.lock.duration.ms. Order within a partition is not guaranteed, so share groups suit processing events one at a time, not streams with dependencies.

An acknowledgement is set on each event: accept (AcknowledgeType.ACCEPT), release (the event will arrive again), reject (it is no longer delivered), or extend the lock (RENEW) if processing takes longer than 30 seconds. The broker counts the delivery attempts: after share.delivery.count.limit attempts (5 by default) the event becomes a candidate for the dead-letter queue (DLQ) — just like rejected events.

javaJava client, share consumer
Properties props = new Properties();props.setProperty("bootstrap.servers", "localhost:9092");props.setProperty("group.id", "jobs-queue");props.setProperty("share.acknowledgement.mode", "explicit");props.setProperty("key.deserializer",    "org.apache.kafka.common.serialization.StringDeserializer");props.setProperty("value.deserializer",    "org.apache.kafka.common.serialization.StringDeserializer");KafkaShareConsumer<String, String> consumer =    new KafkaShareConsumer<>(props);consumer.subscribe(Arrays.asList("jobs"));while (true) {    ConsumerRecords<String, String> records =        consumer.poll(Duration.ofMillis(500));    for (ConsumerRecord<String, String> record : records) {        consumer.acknowledge(record, AcknowledgeType.ACCEPT);    }    consumer.commitSync();}

The dead-letter queue for share groups arrived in Kafka 4.4, is switched on by raising the share.version feature to 2, and is configured on the group: the topic name is set by errors.deadletterqueue.topic.name with the prefix dlq.; if it is not set, the group has no queue. The topic is created in advance, or auto-creation is trusted — it is off by default and is switched on with the cluster setting errors.deadletterqueue.auto.create.topics.enable=true. On a topic created in advance, errors.deadletterqueue.group.enable=true is switched on, otherwise the broker rejects the record; on an auto-created one the flag appears by itself. By default only the event’s metadata is written to it — topic, partition, offset; the key and value are copied by the setting errors.deadletterqueue.copy.record.enable=true:

basha DLQ for a share group
bin/kafka-configs.sh --bootstrap-server localhost:9092 \  --alter --entity-type groups --entity-name jobs-queue \  --add-config errors.deadletterqueue.topic.name=dlq.jobs-queuebin/kafka-configs.sh --bootstrap-server localhost:9092 \  --alter --entity-type topics --entity-name dlq.jobs-queue \  --add-config errors.deadletterqueue.group.enable=truebin/kafka-configs.sh --bootstrap-server localhost:9092 \  --alter --entity-type groups --entity-name jobs-queue \  --add-config errors.deadletterqueue.copy.record.enable=true

Choosing between a classic group and a share group is a choice between order within a partition and flexible distribution of records. How many times an event may be processed on failure is decided by the offset commit and the acknowledgements — see the section “Delivery guarantees and transactions” for details; serialisation of keys and values — in the section “Producers”.

Section sources

the section is written from these pages

Delivery guarantees and transactions

By default, Kafka gives the “at least once” guarantee: an event is not lost, but on a failure it may be processed twice. “Exactly once” is assembled from an idempotent producer, transactions and the read_committed mode; for external systems — databases and HTTP services — Kafka’s guarantees no longer apply.

Two sides are responsible for delivery semantics. The producer decides whether to wait for the broker’s acknowledgement and whether to resend after an error. The consumer decides when to move its position, the offset: before processing a batch or after. It is the order of processing and committing that determines what happens to an event on a failure.

The three delivery guarantees

GuaranteeHow to get itThe price
“At most once”Disable producer retries and commit the offset before processing the batchEvents are lost on a failure between the commit and processing
“At least once”Producer retries are enabled, the offset is committed after processing; this is how Kafka works by defaultDuplicates on a failure between processing and the commit
“Exactly once”A transactional producer with transactional.id plus a consumer in read_committedLatency from transactions; the guarantee does not extend beyond Kafka

Committing the offset before or after processing

Committing the offset moves the group’s position within a partition; it is the only record of what has already been processed. If you commit before processing, a failure right after the commit leaves the batch unprocessed, and reading continues from the next offset — the events are lost. If you commit after processing, a failure between processing and the commit makes a new consumer read the same events again — duplicates appear.

By default, the consumer commits offsets itself, in the background, every 5 seconds (enable.auto.commit=true, auto.commit.interval.ms=5000). Automatic commits are not tied to processing, so an application with strict requirements switches them off and commits manually at the end of a batch. “At most once” is assembled the other way round: the offset is committed before the batch is processed, and producer retries are switched off.

The idempotent producer

On a network error, the producer does not know whether the event reached the broker. Resending protects against loss, but before idempotence is switched on it could have written a second copy to the log. The idempotent producer works differently: the broker issues it an identifier and rejects duplicates by the sequence number the producer sends with every message, so resending does not create duplicates in the log.

The mode is set by enable.idempotence and is switched on by default; it works only with acks=all, with retries enabled and max.in.flight.requests.per.connection of at most 5. Idempotence removes duplicates from retries of a single send, but it does not solve the consumer’s problem: after a crash following processing it will still re-read the batch. An end-to-end guarantee takes transactions.

Transactions

A transaction writes events to several partitions atomically and, crucially, lets you commit the consumer’s offset in the same transaction as the result of processing. Only the producer is transactional, but it updates offsets on behalf of the consumer: the group’s position is stored as events in an internal topic, and writing it is no different from an ordinary write. After a rollback the position returns to its previous value, and the written events are invisible to consumers in read_committed.

  1. initTransactions() — register the producer with the transaction coordinator
  2. beginTransaction() — open a transaction
  3. send() — write the result events to the output topics
  4. sendOffsetsToTransaction() — attach the offsets of the processed batch to the transaction
  5. commitTransaction() — commit the writes and the offsets together; on an error — abortTransaction()

The consumer is given enable.auto.commit=false and isolation.level=read_committed, the producer is given transactional.id: a stable identifier that, when the application restarts, triggers a rollback of the previous instance’s unfinished transaction. Take a separate producer for each consumer instance — this way transactions survive a rebalance predictably. A transaction left open longer than transaction.timeout.ms (1 minute by default) is rolled back by the coordinator itself.

javaapplication settings
// producer: transactions and idempotenceprops.put("transactional.id", "order-copier-1");// consumer: read only committed dataprops.put("isolation.level", "read_committed");props.put("enable.auto.commit", "false");
javacopying a topic into a topic
producer.initTransactions();while (running) {    var batch = consumer.poll(Duration.ofMillis(500));    if (batch.isEmpty()) continue;    // the last offset of the batch plus one    var offsets = new HashMap<TopicPartition, OffsetAndMetadata>();    producer.beginTransaction();    try {        for (var record : batch) {            producer.send(new ProducerRecord<>(                "orders-copy",                record.key(), record.value()));            offsets.put(new TopicPartition(                    record.topic(), record.partition()),                new OffsetAndMetadata(record.offset() + 1));        }        producer.sendOffsetsToTransaction(            offsets, consumer.groupMetadata());        producer.commitTransaction();    } catch (ProducerFencedException e) {        // another instance has taken the same transactional.id        producer.close();        break;    } catch (KafkaException e) {        producer.abortTransaction();        // rollback: reset the position and the state    }}

Rolling back a transaction requires manual rewinding: the consumer does not return to the committed offset by itself — the application resets the position and its own state, after which the batch is processed again. The simplest policy is to discard and recreate the producer and the consumer: the group rebalances and returns to the committed offset.

Since 4.0, brokers use the hardened transaction protocol by default (KIP-890): the producer receives a new epoch for each transaction, so the tail of a previous, aborted transaction does not leak into the next one. The protocol is enabled by the transaction.version=2 flag; clients of version 4.0 and newer switch to it themselves on the next connection.

Kafka Streams

Kafka Streams assembles the same scheme inside the library: the offsets of input topics, state changes and writes to output topics are committed as a single transaction. The guarantee is enabled by the processing.guarantee=exactly_once_v2 setting (the default is at_least_once); the first version of exactly once (exactly_once) was deprecated in the 3.0.0 release and is not accepted in 4.4. By default, transactions require a cluster of at least three brokers — in development this is worked around with the transaction.state.log.replication.factor setting.

propertiesin the Streams configuration
processing.guarantee=exactly_once_v2

Writing to external systems

A Kafka transaction does not cover a database or an HTTP service: the “exactly once” guarantee ends at Kafka’s boundary. For external writes there are two routes. The first is to store the offset where the result is stored: processing and committing the offset then fall into a single transaction of the data store, and no two-phase commit is needed. The second is to make processing idempotent: if an event has a primary key, a repeated write will overwrite the same value, and “at least once” becomes “exactly once” in practice.

What a committed event means to replicas and why it is not lost when a broker fails — see the section “Replication and fault tolerance”. How transactions work in stream processing — see the section “Kafka Streams”.

Section sources

the section is written from these pages

Replication and fault tolerance

Kafka keeps every partition as several copies on different brokers and survives the failure of a broker without stopping writes and reads. Three settings protect against data loss: the replication factor, acks=all on the producer and min.insync.replicas on the topic.

Leader, followers and the ISR

The unit of replication is the partition: Kafka replicates not a topic as a whole but each partition separately. The replication factor sets how many brokers keep its log. The partition leader takes writes and reads; the other copies — followers — fetch events from the leader like ordinary consumers. The replicas’ logs match: the same offsets, the same order of events.

The leader watches who is lagging and maintains the list of in-sync replicas (ISR). It includes the leader and the followers that have reached the end of the leader’s log within replica.lag.time.max.ms (30 seconds by default). A follower falls behind or loses its connection — the leader removes it from the ISR; it catches up — the leader adds it back. An event counts as committed once every replica in the ISR has applied it, and only committed events are read by consumers.

A follower outside the ISR takes no part in acknowledging writes until it catches up with the leader.

The replication factor is set when a topic is created. Factor 2 survives the failure of one broker, factor 3 — two in a row. Production topics get 3; the replicas are spread across brokers so that the leaders are distributed evenly. The factor of an existing topic can be raised later — the replica reassignment tool does it, more on it below.

acks=all and min.insync.replicas

The producer chooses how many replicas to wait for: acks=0 — wait for nobody, acks=1 — wait for the leader, acks=all — every replica in the ISR. acks=all alone does not save you: if only one of three replicas is left in the ISR, the acknowledgement will come from that one alone, and the failure of the last broker loses the data. The lower bound is set by min.insync.replicas, a topic setting (1 by default). With acks=all a write is accepted only while the ISR is at least this number; otherwise the producer receives the NotEnoughReplicas error until the partition regains enough in-sync replicas. The classic pair: factor 3 and min.insync.replicas=2 — a committed event then lives on at least two brokers.

The table sums up what happens when a broker fails in different configurations:

SettingWhat happens when a broker fails
factor 3, min.insync.replicas=1, any acksWrites and reads continue; with acks=all the data is committed on the remaining replicas
factor 3, min.insync.replicas=2, acks=allThe failure of one broker is survived without losses; the failure of two stops writes with NotEnoughReplicas, reads continue
factor 3, min.insync.replicas=3, acks=allThe failure of just one broker already stops writes: the greatest durability, the least availability
factor 1A single copy; a broker failure makes the partition unavailable until it returns, and the data on the failed disk is lost

When the ISR is empty

The “committed is not lost” guarantee holds while at least one replica of the partition is alive in the ISR. If every replica of a partition has died, Kafka by default waits for a replica from the ISR to return — the partition accepts no writes. The unclean.leader.election.enable flag (false by default) allows electing as leader the first replica to return outside the ISR — such elections are called unclean leader election. Writing resumes, but its log becomes the source of truth, and the committed events missing from it are gone.

Since 4.0 the Eligible Leader Replicas (ELR) protocol is in place: the controller also keeps a list of replicas outside the ISR that are safe to make leaders. The order of choice: first a replica from the ISR, then from the ELR, and the former leader last. On new clusters since 4.1 ELR is enabled by default; on existing ones it is turned on with eligible.leader.replicas.version=1, and with it the cluster-wide min.insync.replicas becomes mandatory.

Where replicas live: racks and leaders

If all replicas of a partition sit in one rack, the failure of that rack kills the partition outright. The broker.rack broker option turns on rack awareness: Kafka spreads the replicas of one partition across different racks — one per rack, as many racks as there are. Placement across a cloud’s availability zones works the same way. Keep the number of brokers per rack equal: racks with fewer brokers receive more replicas and more replication traffic.

After a broker fails its partitions move to the others, but the broker that has come back stays a follower: leaders do not come back by themselves. Rebalancing is handled by a background process, switched on by the auto.leader.rebalance.enable flag (enabled by default): it checks the distribution of leaders and returns leadership to the preferred replica — the first in the partition’s replica list. Preferred leaders can be returned by hand with the kafka-leader-election.sh tool:

bashin the Kafka distribution directory
bin/kafka-leader-election.sh \  --bootstrap-server localhost:9092 \  --election-type preferred \  --all-topic-partitions

Moving replicas between brokers is done by kafka-reassign-partitions.sh: it is needed both for servers that have been added and for raising the replication factor of an existing topic. The tool builds a plan, executes it and checks the progress. The section “Topics, partitions and retention” shows creating a topic with factor 3.

Watching replication

A healthy cluster keeps the under-replicated partitions counter at zero: a partition is under-replicated when its ISR is smaller than the full replica list. A non-zero value right after a planned broker restart is normal; if it stays longer than a few minutes, it is already a reason to look at the disk and network of the lagging replica. A quick snapshot comes from the kafka-topics.sh commands:

bashin the Kafka distribution directory
bin/kafka-topics.sh --bootstrap-server localhost:9092 \  --describe --under-replicated-partitionsbin/kafka-topics.sh \  --bootstrap-server localhost:9092 --describe \  --at-min-isr-partitions

Replication metrics in JMX: UnderReplicatedPartitions — partitions whose ISR is smaller than the full replica list; AtMinIsrPartitionCount — partitions at the lower bound; IsrShrinksPerSec and IsrExpandsPerSec — the ISR going up and down; PreferredReplicaImbalanceCount — partitions where the leader is not the preferred one.

The UncleanLeaderElectionsPerSec counter must stay silent: a non-zero value means an unclean election has happened and some committed events may have been lost.

Between clusters replication is arranged differently than inside one: MirrorMaker 2 is in charge — it copies topics and group offsets to another cluster; configuring it is beyond the scope of this reference.

Section sources

the section is written from these pages

Kafka Connect

Kafka Connect is a Kafka component that moves data between Kafka and other systems without any code of your own: databases, files and search indexes are connected with ready-made connectors. The source reads from an external system and writes to a topic; the sink reads from topics and writes to an external system.

Connectors, tasks and workers

A connector is a Java plugin: a description class and a task class that does the actual work. The connector splits the work into tasks; the ceiling is set by tasks.max in the connector configuration, but how many tasks you actually get is up to the connector itself: it may return fewer. For example, a source reading a table by partitions cannot have more tasks than there are partitions.

Tasks run on workers — the Connect processes. The worker records the offsets of what has been read itself, so a connector does not need to duplicate producer and consumer logic; offsets and groups are covered in detail in the section on consumers.

Source and sink mirror each other: the former writes to Kafka, the latter reads from Kafka.

Standalone and distributed

The mode is set by how the worker is started, not by the connector. In standalone everything runs in a single process — an option for trying things out and for cases where one worker is the whole workload, such as collecting files from a single machine. There is no fault tolerance: if the process dies, the entire transfer stops. Source task offsets are stored in a local file whose path is set by offset.storage.file.filename.

In distributed, workers with a shared group.id form a cluster: tasks are distributed automatically — add a worker and Connect moves part of the tasks to it, remove one and it takes them back. A worker failure is survivable: its tasks are restarted on the others, so production setups run at least two workers on separate machines.

bashin the Kafka directory, on the host
# Worker and connectors from filesbin/connect-standalone.sh \  config/connect-standalone.properties \  config/connect-file-source.properties # Connect cluster; connectors only via the REST APIbin/connect-distributed.sh config/connect-distributed.properties

Internal topics

In distributed mode, workers store their state in three Kafka topics. The documentation recommends creating them in advance to set the right number of partitions and the replication factor.

TopicWhat it storesHow to configure
config.storage.topicconnector and task configurationsone partition, compaction, replicas
offset.storage.topicsource task offsetsmany partitions, compaction, replicas
status.storage.topicconnector and task statusesseveral partitions, compaction, replicas

If the topics do not exist at startup, the worker creates them itself with default settings. This is controlled by internal.topics.automatic.creation.enable (introduced in Kafka 4.4, true by default): it covers the three worker topics and the dedicated offset topics of source connectors (offsets.storage.topic in the connector configuration). With false, the worker does not create the topics and will not start until they exist; the connect-internal-topics.sh utility helps create them manually.

REST API

In distributed mode, connectors are created, read and deleted only through the REST API; by default the worker listens on port 8083, and the listeners setting changes the port. The API is also available in standalone: there, connectors can be described in files on the command line and created through the REST API. The list of installed plugins is shown by GET /connector-plugins.

bashon a host with access to the worker
curl -s http://localhost:8083/connectors curl -s http://localhost:8083/connectors/file-source/status curl -s -X POST \  "http://localhost:8083/connectors/file-source/restart?includeTasks=true&onlyFailed=true"
bashcreating a connector
curl -s -X POST http://localhost:8083/connectors \  -H "Content-Type: application/json" \  -d '{    "name": "file-source",    "config": {      "connector.class": "FileStreamSource",      "tasks.max": "1",      "file": "/tmp/input.txt",      "topic": "files"    }  }'

The status comes for the connector and for each task separately: UNASSIGNED, RUNNING, PAUSED, FAILED, RESTARTING; the connector can also have STOPPED — the state after stop, tasks have no such status. Connect does not restart failed tasks itself — that is what POST /connectors/{name}/restart with onlyFailed=true is for. During a rebalance the restart returns 409 Conflict: wait and retry. A failure shows in the status, the metrics or the consumer lag — see the section on common mistakes.

Other methods: PUT /connectors/{name}/pause pauses the connector while keeping the task resources occupied; PUT /connectors/{name}/stop stops the tasks and frees them. Offsets are shown by GET /connectors/{name}/offsets; changing them via PATCH /connectors/{name}/offsets is only possible for a stopped connector.

Converters

The converter (key.converter, value.converter) is set in the worker configuration and translates the internal Connect format into bytes for Kafka and back, so the record format does not belong to the connector: a single connector can work with JSON or Avro alike. There is one converter for all connectors of a worker; an individual connector changes the format through its own key.converter and value.converter in its configuration.

The shipped worker configs specify org.apache.kafka.connect.json.JsonConverter with schemas.enable=true: every message carries both the data and the schema. For readable topics without schemas, turn it off:

propertiesconnect-distributed.properties
key.converter=org.apache.kafka.connect.json.JsonConvertervalue.converter=org.apache.kafka.connect.json.JsonConverterkey.converter.schemas.enable=falsevalue.converter.schemas.enable=false

With schemas enabled, JsonConverter embeds the schema in every message, while the Avro, Protocol Buffers and JSON Schema converters work with an external schema registry. Schema registries are outside the scope of this reference.

Single message transforms (SMT)

A single message transform (SMT) changes every message on the path between the connector and the topic. The built-in transforms are enough for typical cases; for transforms that work with the key or the value, the value class is written with the $Value suffix and the key one with $Key.

TaskTransform
rename or remove a fieldReplaceField
new field from metadata or a constantInsertField
build the key from value fieldsValueToKey
wrap the value in a single fieldHoistField
keep a single field instead of the structureExtractField
change the type of a field or the whole valueCast
convert time between formatsTimestampConverter
flatten a nested structureFlatten
replace values with type-appropriate blanksMaskField
rename the topic by regular expressionRegexRouter
route records to topics by timeTimestampRouter
drop messages (with a predicate)Filter
jsona snippet of connector configuration
"transforms": "MakeMap, AddSource","transforms.MakeMap.type":  "org.apache.kafka.connect.transforms.HoistField$Value","transforms.MakeMap.field": "line","transforms.AddSource.type":  "org.apache.kafka.connect.transforms.InsertField$Value","transforms.AddSource.static.field": "data_source","transforms.AddSource.static.value": "file-source",

The order of transforms is set by the transforms list: the string is first wrapped into the line field, then gets the data_source field. A predicate is declared in predicates and predicates.$alias.type and assigned to a transform with the predicate key; with negate=true, the transform applies to all records except the matching ones — for example, all records except those of one topic.

Errors and DLQ

By default, Connect is fail fast: errors.tolerance is none, and the first conversion, transform or sink write error stops the task. For sinks, where a bad message should not stop the flow, you enable tolerance and a dead letter queue (DLQ):

propertiessink connector configuration
errors.tolerance=allerrors.log.enable=trueerrors.log.include.messages=falseerrors.deadletterqueue.topic.name=dlq-file-sinkerrors.deadletterqueue.context.headers.enable=true

errors.tolerance=all skips the problematic records; with errors.log.enable=true, the details of each error go to the worker log, and the record itself goes to the DLQ topic. With errors.deadletterqueue.context.headers.enable=true, the error context is written into record headers with the __connect.errors. prefix. The errors.log.include.messages=true key adds the record key, value and headers to the log — personal data may end up in the log along with them, which is why it is off by default. Retries on write failures are configured by errors.retry.timeout.

Where to get connectors

Kafka ships only the educational file connectors (FileStreamSourceConnector and FileStreamSinkConnector) in connect-file-4.4.0.jar; they are not included in the worker’s plugin.path. Working connectors for databases, stores and queues come from vendors and the community: find a ready-made JAR for your system and put it into plugin.path — each plugin in its own subdirectory, so that the worker keeps its classes apart from the neighbours and does not mix library versions. After installation, check that the plugin is visible via GET /connector-plugins.

Section sources

the section is written from these pages

Kafka Streams

Kafka Streams is a client library for Java that processes events from topics inside your own application: it filters, joins and aggregates streams. There is no separate server and no cluster is needed: scale the application simply by launching new instances.

A library, not a cluster

A Kafka Streams application is an ordinary Java program with the org.apache.kafka:kafka-streams dependency: it runs on a virtual machine, in a container, in Kubernetes. The library distributes the work between instances and restores it after a failure by itself — a separate processing cluster, like the one heavy stream processing systems need, is not required.

The number of partitions of the input topic sets the scale: the topology is split into tasks (stream task), one per partition, and the application instances share the tasks between themselves. Maximum parallelism equals the number of partitions: spare instances wait in reserve and take over the tasks of a neighbour that has failed.

Topology: sources, processors and sinks

The processing logic is described by a topology — a graph of processors and the streams between them. A source (source processor) reads events from topics and has no predecessors, an ordinary processor receives one event at a time from the preceding nodes and passes the result on, and a sink (sink processor) writes events to the output topic.

An event in a stream is a key–value pair. A stream is an endless, ordered sequence of such pairs within a partition: this is exactly what Kafka stores as a log (see the section “Topics, partitions and retention”).

  • the source reads the input topics and passes every event to the first processor;
  • processors transform the events one at a time: stateless or with local state;
  • the sink writes the result to the output topic.
Each partition is processed by its own task; the library shares the tasks between instances.

KStream and KTable

The DSL has two key abstractions, and the difference between them is a beginner’s main source of mistakes. KStream is a stream of events: each record stands on its own, like a log line — “add another one”. KTable is a table whose changelog is kept in a topic: a record with the same key replaces the previous one — “update the value”.

An example from the documentation: the pairs (“alice”, 1) and then (“alice”, 3) arrive in a topic. Summing over a KStream gives 4: the second record is a new event. Over a KTable the result is 3: the record updates the previous value. This gives a storage rule: keep an aggregation result (KTable) in a compacted topic (see the section “Topics, partitions and retention”); with a KStream, compaction would lose events.

Streams and tables convert into each other: KTable.toStream() turns the table’s changes into a stream, and aggregating a stream produces a table. Recovery of state after a failure also rests on this duality (stream-table duality).

Stateless and stateful operations

Stateless operations process each event on its own: filter, mapValues, flatMapValues, branching. They need no state. Stateful operations remember past events: groupByKey and groupBy gather events by key, count, aggregate and reduce maintain aggregates, and join combines streams and tables.

If a key has changed, events of one aggregation end up in different partitions — the library creates an internal repartition topic. Events with the same key are always processed by one application instance — a consumer group works in the same way (see the section “Consumers and groups”).

OperationTypeWhat it does
filterstatelesspasses through events for which the predicate holds
mapValuesstatelesschanges the value, keeping the key and the order
flatMapValuesstatelessexpands one event into several
groupByKeystatefulgathers events by key; a changed key means repartitioning
countstatefulcounts the events of each key
aggregatestatefulfolds events into an accumulated value
joinstatefuljoins a stream with a stream, a table or a global table

State stores and the changelog

State is stored locally, next to the task — by default in the built-in RocksDB key–value store, in the state.dir directory. The store survives failures: for every store the library maintains a changelog topic, compacted by keys, like the log of the table itself (see the section “Topics, partitions and retention”). A task that has lost its instance restarts on another one, and the empty store is restored by reading the changelog from the beginning. The larger the state, the longer the recovery; standby copies of the state on other instances shorten it (num.standby.replicas).

Windows and event time

To aggregate “per minute” or “per hour”, use windows: a tumbling window defines fixed, non-overlapping intervals, a hopping window moves with a step smaller than its size, and a session window groups the events of a key until the gap between them exceeds the inactivity threshold.

The time of a window is event time, not processing time: the timestamp of the record from the topic. Late records still land in their own window while the grace period has not expired; after the window closes, the record is discarded. You set the grace period together with the window: TimeWindows.ofSizeAndGrace or SessionWindows.ofInactivityGapAndGrace.

Counting events by key

The reference example is a per-key event counter: we read the events topic, count by the user key and write the running total to events-count.

xmlpom.xml
<dependency>  <groupId>org.apache.kafka</groupId>  <artifactId>kafka-streams</artifactId>  <version>4.4.0</version></dependency>
javaJava
Properties props = new Properties();props.put(StreamsConfig.APPLICATION_ID_CONFIG, "events-count");props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG,    Serdes.String().getClass());props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG,    Serdes.String().getClass()); StreamsBuilder builder = new StreamsBuilder();builder.stream("events", Consumed.with(Serdes.String(), Serdes.String()))    .filter((key, value) -> value != null)    .groupByKey()    .count(Materialized.as("events-count-store"))    .toStream()    .to("events-count", Produced.with(Serdes.String(), Serdes.Long())); KafkaStreams streams = new KafkaStreams(builder.build(), props);Runtime.getRuntime().addShutdownHook(new Thread(streams::close));streams.start();

Run two instances of the application: the library itself will divide the partitions of the events topic between them and, when one instance stops, move its tasks to the other.

Rebalancing and guarantees

The rebalancing protocol determines how tasks are distributed: by default the application works as a consumer group (group.protocol = classic), while the value streams turns on the streams-group protocol — coordination on the broker and faster rebalances; it requires support on the broker side. The processing.guarantee setting sets the delivery guarantee: at-least-once by default, while the value exactly_once_v2 makes writing results and offsets atomic (see the section “Delivery guarantees and transactions”).

TaskSetting
Processing threads per instancenum.stream.threads
Processing guaranteeprocessing.guarantee = exactly_once_v2
Standby copies of the statenum.standby.replicas
New rebalancing protocolgroup.protocol = streams
Local state directorystate.dir

Section sources

the section is written from these pages

Security

By default, Kafka brokers and clients communicate without encryption or authentication: every listener accepts connections from the whole network. An open PLAINTEXT listener is the main threat to a cluster: a client that connects to it reads and writes events at will. Encryption and authentication come from listener settings, while an access control list restricts what clients may do.

Listeners and protocols

The broker accepts connections on listeners — entries such as CLIENT://0.0.0.0:9092 in the listeners list. Each listener runs one of the four security protocols defined in listener.security.protocol.map. Encryption and authentication belong to the listener, not to the client: broker-to-broker traffic and client traffic are kept separate, so listeners are set up on different ports.

ProtocolEncryptionClient authenticationWhere it fits
PLAINTEXTnonenoneonly inside a trusted network
SSLTLScertificates, optionalencryption, clients with certificates
SASL_PLAINTEXTnoneSCRAM, Kerberos and othersauthentication without TLS
SASL_SSLTLSSASL over TLSproduction, external clients

The listener also determines what the broker advertises to clients: on connecting, clients receive the address from advertised.listeners and keep using it afterwards. If it holds an internal name or localhost, external clients cannot connect. The inter-broker listener is set by inter.broker.listener.name — replication runs over it (see the section “Replication and fault tolerance”); the controller listener is set by controller.listener.names.

propertieshow not to do it
listeners=PLAINTEXT://0.0.0.0:9092advertised.listeners=PLAINTEXT://kafka.example.org:9092

The listener is open on all interfaces, without encryption or authentication: whoever reaches the port can read, write and manage the cluster. This is done only in an isolated test bench with a fully trusted network.

propertieshow to do it right
listeners=CLIENT://0.0.0.0:9093advertised.listeners=CLIENT://kafka.example.org:9093listener.security.protocol.map=CLIENT:SASL_SSLssl.client.auth=required

Traffic is encrypted, the client is authenticated by a SASL mechanism and an mTLS certificate, and permissions are restricted by StandardAuthorizer — these settings are covered below.

TLS encryption

The SSL protocol encrypts the connection with TLS. The broker needs two stores: a keystore with its own certificate and private key, and a truststore with the certificate of the certificate authority. The client keeps a certificate from the same authority in its truststore. Since Kafka 2.7, stores can be specified directly in the configuration in PEM format. The store file type is set by ssl.keystore.type: JKS by default, with PKCS12 and PEM also supported.

propertiesthe broker’s server.properties
listeners=CLIENT://0.0.0.0:9092listener.security.protocol.map=CLIENT:SSLssl.keystore.type=PKCS12ssl.keystore.location=/etc/kafka/tls/broker.keystore.p12ssl.keystore.password=change-messl.key.password=change-messl.truststore.type=PKCS12ssl.truststore.location=/etc/kafka/tls/broker.truststore.p12ssl.truststore.password=change-me

For the client, trust in the certificate authority is enough:

propertiesthe consumer’s client.properties
security.protocol=SSLssl.truststore.type=PKCS12ssl.truststore.location=/etc/kafka/tls/client.truststore.p12ssl.truststore.password=change-me

From Kafka 2.0, the client verifies the host name in the broker’s certificate: the SAN field must match the connection address, otherwise the handshake is aborted. That is why the broker’s certificate is requested with a SAN holding the real DNS names (-ext SAN=DNS:kafka1.example.org). Disabling the check with an empty ssl.endpoint.identification.algorithm opens the way to man-in-the-middle attacks, so this is not recommended.

Mutual authentication

By default ssl.client.auth=none: the broker verifies only its own certificate. The value required demands a certificate signed by a trusted authority from every client. This is mutual authentication (mTLS): the name in the client’s certificate becomes its principal for the access control list. The value requested makes the check optional: a client without a certificate will still connect, and the setting only creates an appearance of protection.

SASL authentication

The SASL_SSL and SASL_PLAINTEXT protocols add authentication to the connection through SASL mechanisms: SCRAM-SHA-256, SCRAM-SHA-512, PLAIN, OAUTHBEARER and GSSAPI (Kerberos). The list of mechanisms is set by sasl.enabled.mechanisms, and for inter-broker traffic by sasl.mechanism.inter.broker.protocol. Client credentials are passed in the sasl.jaas.config property, broker credentials in a property prefixed with the listener and mechanism name: listener.name.sasl_ssl.scram-sha-256.sasl.jaas.config.

MechanismHow it authenticatesWho it suits
SCRAM-SHA-256name and password, the password is not transmitteda good fit for production
SCRAM-SHA-512the same with a stronger hashwhere SHA-512 is required
PLAINname and password in plain textonly over TLS; the broker sees the password
OAUTHBEARERa JWT token from an OAuth 2 providerintegration with a corporate provider
GSSAPIKerberosKerberos domains

SCRAM accounts are stored in the cluster’s metadata log. kafka-storage.sh creates them when formatting the storage, kafka-configs.sh on a running cluster. If brokers or the administrator log in only with SCRAM, the accounts must be created before the first start: otherwise nobody will be able to log into the cluster.

bashformatting the storage with an account
bin/kafka-storage.sh format -t $(bin/kafka-storage.sh random-uuid) \    -c config/server.properties \    --add-scram 'SCRAM-SHA-256=[name="admin",password="admin-secret"]'
basha client account on a running cluster
bin/kafka-configs.sh --bootstrap-server localhost:9092 --alter \    --add-config 'SCRAM-SHA-256=[iterations=8192,password=alice-secret]' \    --entity-type users --entity-name alice \    --command-config admin.properties

The client connects with a mechanism and credentials:

propertiesthe producer’s client.properties
security.protocol=SASL_SSLsasl.mechanism=SCRAM-SHA-256sasl.jaas.config=org.apache.kafka.common.security.scram.ScramLoginModule \    required username="alice" password="alice-secret";

The PLAIN mechanism sends the name and password in plain text, so it is only suitable over TLS (that is, SASL_SSL). SCRAM works differently: the password never travels over the network, and the broker stores not the password itself but a salted verification string.

Authorisation and ACLs

An access control list (ACL) decides who is allowed to do what. It is handled by the class from authorizer.class.name; for KRaft this is StandardAuthorizer, which keeps ACL entries in the metadata log. An entry has the form “who — operation — on what”: for example, “the user alice is allowed to read the topic orders”. Without a matching entry, access is denied to everyone except the super users from super.users — with authorisation enabled, only what is explicitly allowed works.

propertiesserver.properties
authorizer.class.name=org.apache.kafka.metadata.authorizer.StandardAuthorizersuper.users=User:admin

Entries are added with the kafka-acls.sh utility. Permission to write to a topic:

bashproducer permissions on a topic
bin/kafka-acls.sh --bootstrap-server localhost:9092 \    --add --allow-principal User:alice \    --producer --topic orders

Permission to read. A consumer also needs the group:

bashconsumer permissions on the topic and the group
bin/kafka-acls.sh --bootstrap-server localhost:9092 \    --add --allow-principal User:alice \    --consumer --topic orders --group report-workers

The --producer option grants WRITE, DESCRIBE and CREATE on the topic, --consumer — READ and DESCRIBE on the topic plus READ on the group. Listing entries is --list, removal is --remove. A principal name is written as User:alice.

The three layers of protection work together: TLS encrypts the traffic, SASL verifies who has connected, and the ACL decides what they may do. The combination of SASL_SSL and StandardAuthorizer covers all three.

How to keep passwords out of configuration files — in the Docker reference, the section “Builds: cache, multi-stage and secrets”. TLS, X.509 certificates and certificate authorities — the TLS and PKI reference, the sections “X.509 certificates” and “Mutual authentication (mTLS)”. OAuth 2 flows — the OAuth and OIDC reference, the section “Flows: authorization code, PKCE and others”.

Section sources

the section is written from these pages

Common errors and troubleshooting

Start diagnostics in three places: the broker log, the state of the topic and the state of the group. A client error most often names a code such as NOT_ENOUGH_REPLICAS — below, the cause and the first action can be found by that code.

Where to start

The broker log answers the question “what happened on the server”: leader changes, replicas leaving the list of in-sync replicas (ISR) and unavailable log directories are visible there. The tools kafka-topics.sh and kafka-consumer-groups.sh show the rest: where the leaders and replicas of the partitions are now, and how far behind the group is reading.

bashthe state of the partitions
bin/kafka-topics.sh --bootstrap-server localhost:9092 \  --topic orders --describe
textexample output
Topic: orders  Partition: 0  Leader: 1  Replicas: 1,2,3  Isr: 1,2Topic: orders  Partition: 1  Leader: 2  Replicas: 2,3,1  Isr: 2,3,1

In the example, the leader of partition 0 is broker 1, and two of the three replicas are in sync: broker 3 has fallen behind or is unavailable. While a partition has no leader, nothing is written to it — the cluster elects one.

bashthe group’s lag
bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 \  --describe --group billing
textexample output
GROUP    TOPIC   PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG  CONSUMER-IDbilling  orders  0          410             415             5    consumer-1-8c2f...billing  orders  1          407             512             105  -

The LAG column shows how many events the group is behind by. An empty CONSUMER-ID means the partition is assigned to nobody — the group is rebalancing or its members have disconnected; --state shows the state of the group as a whole.

NOT_LEADER_OR_FOLLOWER and LEADER_NOT_AVAILABLE

Both errors mean the request did not reach the current leader: an election is under way for the partition, or another broker has become the leader. Usually everything settles on its own: the client refreshes the metadata and repeats the request to the new leader. The problem is when the errors keep repeating for minutes: that is a sign of leaders changing constantly. Look for the cause on the broker side: restarts, memory shortage, a disk with high latency. The broker log shows exactly when the leaders changed.

UNKNOWN_TOPIC_OR_PARTITION

The broker the client contacted does not serve this partition. This is normal during a leader election, after the number of partitions has changed and until the client’s metadata is refreshed. If the error does not go away, compare the name with kafka-topics.sh --list. Common causes: the topic does not exist, there is a typo in the name, or the topic was created recently and its metadata has not reached the client yet.

MESSAGE_TOO_LARGE

The event does not go through on writing: the size of the record batch exceeds one of the limits. There are three limits on the write path, and all three must let the event through; the fourth row of the table is the consumer’s limit when reading:

WhereSettingDefault
producermax.request.size1048576
brokermessage.max.bytes1048588
topicmax.message.bytessame as the broker
consumermax.partition.fetch.bytes1048576

The consumer setting is special: if the first batch of records in a partition is larger than the limit, the broker returns it anyway, so that the consumer can move on. Compression affects the comparison: the producer compares the batch with the limit before compression, the broker after compression, if compression is on.

bashraise the topic’s limit
bin/kafka-configs.sh --bootstrap-server localhost:9092 \  --entity-type topics --entity-name orders --alter \  --add-config max.message.bytes=10485760

NOT_ENOUGH_REPLICAS

A producer with acks=all is refused: the in-sync replicas (ISR) are fewer than min.insync.replicas on the topic. Nothing is written — this is protection against data loss if another broker fails, not an error. Look at how many replicas are in the ISR and where the lagging ones are: kafka-topics.sh --describe above. Fix the cause — a slow disk, a restarted broker, the network — rather than lowering min.insync.replicas. JMX metrics watch over this state. UnderReplicatedPartitions — partitions whose in-sync replicas are fewer than the full list. UnderMinIsrPartitionCount — partitions below min.insync.replicas, where writing is no longer possible.

REBALANCE_IN_PROGRESS

The group is rebalancing — the partitions are being reassigned to the members. One-off rebalances are normal: a member has left or joined. Frequent rebalances mean consumption is being disrupted: processing in the poll() loop takes longer than max.poll.interval.ms (5 minutes by default). The coordinator takes a silent member for dead, evicts it and assembles the group anew; the member returns and triggers a rebalance again. Increase max.poll.interval.ms, reduce max.poll.records, or move long processing out of the polling loop.

javaa longer loop, a smaller batch
props.put("max.poll.interval.ms", "600000");props.put("max.poll.records", "100");

The client connects, but nothing works after that

The connection is established, the metadata has been received, but the producer or the consumer gets no replies. A common cause is a wrong advertised.listeners on the broker: the client is told an address at which the broker is unreachable from outside, for example localhost in a Docker container or an internal host name. From the client machine, check that the client can reach the advertised address: on Linux, nc -vz kafka.example.org 9092.

propertiesthe broker’s server.properties
advertised.listeners=PLAINTEXT://kafka.example.org:9092

The consumer is falling behind

Growing lag means the consumer cannot keep up with the producers. First make sure rebalances are not the cause: frequent rebalances stop the reading of all members, while a single lagging member is visible in --describe. Then work through the typical causes:

  • Processing a single event takes too long — profile the code and move the heavy steps out of the polling loop.
  • There are more partitions than members — add members up to the number of partitions.
  • The broker responds slowly — look at RequestHandlerAvgIdlePercent: normally it is above 0.3.

A one-off plateau after the consumer has been down for a long time is normal: the group is catching up with the tail. When there is no need to catch up, offsets are reset closer to the end of the log — the commands are in the section “Cheat sheet”. For max.poll.records batch sizes, see the section “Consumers and consumer groups”.

The broker’s disk is full

Partition logs grow until retention stops them — retention.ms and retention.bytes on the topic — or the disk overflows. Watch the free space on the disks with log.dirs and the OfflineLogDirectoryCount metric: a non-zero value means a log directory is unavailable. BytesInPerSec shows the rate at which data grows.

Tools for deeper diagnostics

kafka-metadata-quorum.sh describe --status shows the state of the metadata quorum: who the active controller is and how far the followers have fallen behind. If the controller is unavailable or the quorum fails to form, the metadata is not updated — topics and leaders “freeze”. kafka-dump-log.sh can decode the records of the metadata log and of a topic’s segments.

bashthe state of the quorum
bin/kafka-metadata-quorum.sh --bootstrap-server localhost:9092 \  describe --status
bashmetadata log records
bin/kafka-dump-log.sh --cluster-metadata-decoder \  --files /var/kafka-logs/__cluster_metadata-0/00000000000000000000.log

Section sources

the section is written from these pages

Versions and what’s new

This reference covers Apache Kafka 4.4: the latest release, 4.4.0, came out on 22 October 2026. The project aims for three releases a year; patch releases come out as needed and only for supported branches. A new branch is installed with a rolling upgrade: brokers are replaced one at a time, and the cluster keeps running.

A release number reads as follows: 4.4 is the branch, 4.4.0 is the first release of the branch, and 4.4.1 onwards are fixes without new features. No support timelines are announced: the downloads page lists the supported releases, and the rest are archived.

BranchStatusFirst releaseLatest release
4.4current, receives releases4.4.0 — 22 October 20264.4.0 — 22 October 2026
4.3supported4.3.0 — 22 May 20264.3.2 — 23 October 2026
4.2supported4.2.0 — 17 February 20264.2.2 — 29 September 2026
4.1archived, no fixes4.1.0 — 2 September 20254.1.2 — 17 March 2026

The broker, client libraries and utilities ship as one set with a shared version number; the Docker images apache/kafka and apache/kafka-native are published under the same number. How to install a release — the section “Installation and first run”.

What changed in 4.4

The main changes in 4.4 compared with 4.3:

  • A dead letter queue (DLQ) for share groups: records that have exhausted their delivery attempts or been rejected by the consumer go to a topic with the prefix dlq.; delivery is enabled by the share.version=2 flag. See the section “Consumers and consumer groups”.
  • kafka-cluster.sh api-versions shows the API versions of brokers and controllers: the utility accepts both --bootstrap-server and --bootstrap-controller. See the section “Cheat sheet”.
  • A controller can be removed from cluster metadata: the command kafka-cluster.sh unregister-controller and the --unregister flag of kafka-metadata-quorum.sh remove-controller; metadata version 4.4-IV2 is required. See the section “Architecture: brokers and KRaft”.
  • Asynchronous resolution of bootstrap.servers: the client setting bootstrap.resolve.timeout.ms with a value greater than zero makes the constructor non-blocking, and DNS errors surface later. The feature is still evolving; Streams and Connect do not support it yet.
  • A broker with OAUTHBEARER and a configured JWKS URL does not start until sasl.oauthbearer.expected.audience and sasl.oauthbearer.expected.issuer are set. See the section “Security”.
  • Kafka Streams supports static membership (group.instance.id) in the streams group protocol: brokers and clients no older than 4.4 are required. See the section “Kafka Streams”.

Deprecated and removed

Nothing has been removed in 4.4; all deprecations concern Kafka 5.0:

  • The broker.id setting is deprecated — use node.id. From 5.0 onwards, tiered storage plugins will stop receiving the old name too.
  • kafka-broker-api-versions.sh is deprecated: use kafka-cluster.sh api-versions; the old utility will be removed in the next major release.
  • The ClientQuotaCallback#updateClusterMetadata method is deprecated: overriding it in your own implementations is no longer needed, as a default implementation has been added.
  • The kafka-streams-scala library has been deprecated since 4.3 and will be removed in 5.0.

Security updates

Vulnerabilities are listed on the project’s CVE List page. On 28 October 2026, twelve CVEs were announced at once: eleven were fixed in releases 4.2.2, 4.3.1, 4.3.2 and 4.4.0, and CVE-2026-110952 only in 4.4.0; earlier CVEs were fixed in patch releases of earlier branches:

Fixed inWhat was fixed
4.2.2, 4.3.2, 4.4.0Denial of service on the broker through unbounded memory allocation: compressed batches — CVE-2026-114349, request parsing — CVE-2026-111108 and CVE-2026-111115. A single update is not enough for CVE-2026-114349: set the max.decompressed.message.bytes limit; by default it is effectively unlimited (about 2 GiB)
4.2.2, 4.3.2, 4.4.0Reading files and environment variables of the broker without the required permissions — CVE-2026-112375; authentication bypass of the Connect admin listener — CVE-2026-115644; leakage of connector secrets through the validate endpoint — CVE-2026-116593
4.2.2, 4.3.2, 4.4.0Crash of the KRaft controller with a FetchSnapshot request — CVE-2026-83525; hang of a Streams processing thread — CVE-2026-111496; denial of service against Streams and consumers through deserialisation — CVE-2026-111551
4.2.2, 4.3.1, 4.4.0PushTelemetry telemetry decompresses the payload without a size limit — CVE-2026-111073; OAUTHBEARER does not verify the JWT signature when no JWKS URL is set — CVE-2026-110985
4.4.0SASL/OAUTHBEARER: the token issuer and audience were not verified by default — CVE-2026-110952; a 4.4 broker does not start without the expected values
3.9.2, 4.0.2, 4.1.2, 4.2.0Producer messages silently went to someone else’s topic because of a buffer race — CVE-2026-35554
4.1.2, 4.2.0OAUTHBEARER accepted any JWT without verifying the signature, issuer or audience — CVE-2026-33557
3.9.2, 4.0.1, 4.1.0The client’s DEBUG-level log printed requests together with secrets — CVE-2026-33558

One entry with no code fix: the CONSUMER_GROUP_DESCRIBE API checks the DESCRIBE permission on the group rather than READ, as the documentation and KIP-848 had promised. Check the ACLs of your groups against the principle of least privilege — how to do that is covered in the section “Security”.

How to upgrade

Upgrading to 4.4 works from versions 3.3.x–4.3.0 as a rolling upgrade. A cluster in ZooKeeper mode cannot be upgraded: first migrate to KRaft on the 3.9 branch — details in the section “Architecture: brokers and KRaft”.

  1. On a single broker: stop the process, replace the release (archive, package or Docker image — the section “Installation and first run”) and start it again.
  2. Check that the cluster is working as before: partitions have leaders and replication is not lagging — monitoring commands in “Cheat sheet”.
  3. Repeat on the remaining brokers, one at a time.

When all brokers are running 4.4, finish the upgrade:

bashon the host, in the Kafka directory
bin/kafka-features.sh --bootstrap-server localhost:9092 \  upgrade --release-version 4.4

The command raises the cluster’s feature versions to level 4.4. Rolling the metadata version back is possible only if there are no metadata changes between the versions; before deciding on a rollback, check the Upgrading page.

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 4 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Manual edit

    reason: manual edit
  4. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

18 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “Kafka” topic
13 sections
Another reference · Backend

Python

Verified 31 Oct
All references · 61