Introduction: A Log First, a Broker Second
Most messaging systems are built around a queue. The broker holds messages, hands each one to a consumer, remembers which were acknowledged, and deletes them once they are. Kafka is built around a different object. Its design document lists the jobs it was meant to do (high-volume event streams, large backlogs for offline loads, low-latency delivery, partitioned real-time processing, and survival of machine failures) and says that doing all of them "led us to a design with a number of unique elements, more akin to a database log than a traditional messaging system."1
The unit of that design is the partition: an append-only, totally ordered sequence of records, each identified by a 64-bit offset.2 Producers append to the end. Consumers read forward from an offset of their choosing, so a reader's whole state is "just a single integer, the offset of the next message to consume."1 The broker keeps no per-message delivery state and does not delete a record because somebody read it. It keeps data for a configured time or size, which is what lets a consumer rewind and read it again.1 A topic is a named set of partitions. Partitions are how the log is spread across machines and how a group of consumers splits the work.
Three constraints explain most of what follows. The first is volume. The original workload was web activity data, where "each page view may generate dozens of writes" and every message is read at least once and often several times, so both ends of the pipeline have to be cheap.1 The second is how disks and kernels behave: sequential I/O is far faster than random I/O, and the operating system already uses all free memory to cache file data.1 The third is the JVM, where object overhead often doubles the size of the data and garbage collection slows down as the heap grows.1 Kafka gives one answer to all three. It keeps message data out of the heap, writes it sequentially to plain files in the format it arrived in, lets the page cache hold the recent tail, and moves bytes between disk and network in large batches without parsing them.1
The same structure is then reused for everything else. Followers replicate by fetching from the leader "just as a normal Kafka consumer would".1 Committed consumer offsets, transaction state and share-group state are records in internal topics.3, 4, 5 Since Apache Kafka 4.0 the cluster's own metadata is a replicated log too, kept by a Raft-based controller quorum called KRaft. ZooKeeper mode was removed in that release.5
This paper follows the data path: the log on disk (Section 1), the producer (Section 2), the broker's request handling (Section 3), replication (Section 4), the KRaft control plane (Section 5), and consumers, groups and queues (Section 6). It then compares Kafka with its nearest alternatives. Version-dependent statements describe Apache Kafka 4.4.0, announced on 22 October 2026, and were checked against the documentation and source at that release tag.6 Where a default or a protocol changed during the 4.x line, the release is named.
Section 1: The Log on Disk
1.1 A partition is a directory of segments
On disk a partition is a directory named after the topic and the partition number, so a topic orders with two partitions is the directories orders-0 and orders-1.2 Inside, the log is cut into segments. A segment is a .log file plus its index files, and every file is named after the offset of the first record in the segment, zero-padded to 20 digits.2 Appends go only to the last segment, the active one. It is closed and a new one opened when it reaches segment.bytes (1 GiB by default) or segment.ms (seven days).2, 7
orders-0/ 00000000000000000000.log record batches, offsets 0 .. 52,340 00000000000000000000.index offset -> byte position (sparse) 00000000000000000000.timeindex timestamp -> offset (sparse) 00000000000000052341.log next segment, named by its first offset 00000000000000052341.index 00000000000000052341.timeindex 00000000000000052341.txnindex aborted transactions, if there were any 00000000000000104729.log active segment: every append lands here 00000000000000104729.index 00000000000000104729.timeindex 00000000000000104729.snapshot producer state (Section 2.4) leader-epoch-checkpoint leader epoch -> first offset (Section 4.4)
Segments keep both retention and lookup cheap. Retention deletes whole files and never rewrites one. A read finds its segment by a binary search over the in-memory list of base offsets and then looks inside a single file.2
Using the offset as the record's identity was a deliberate simplification. The first idea was a GUID generated by the producer, but that needs a GUID-to-position map on every broker, "essentially requiring a full persistent random-access data structure", which is the thing the log was chosen to avoid. A per-partition counter needs no lookup structure beyond "which file, and where in it".2
1.2 The record batch
Records are never written one at a time. The unit on the wire, on disk and in replication is the record batch: a fixed header, 61 bytes if you add up the fields, followed by one or more records.8
baseOffset int64 offset of the first record, set by the leader
batchLength int32
partitionLeaderEpoch int32 set by the leader on append
magic int8 2
crc uint32 CRC-32C over everything below this line
attributes int16 codec (bits 0-2), timestamp type,
isTransactional, isControlBatch
lastOffsetDelta int32
baseTimestamp int64
maxTimestamp int64
producerId int64 \
producerEpoch int16 } idempotence and transactions (Section 2)
baseSequence int32 /
recordsCount int32
records [Record] offsets and timestamps as varint deltas;
compressed together when a codec is set
The layout serves the hot path. The producer, the broker and the consumer share this one binary format "so data chunks can be transferred without modification between them."1 A leader therefore appends the bytes it received and later sends the same bytes out. What it adds on append is the batch's base offset and its own leader epoch.8, 9 Both fields sit in front of the checksummed region, and the documentation says the leader epoch is left out of the CRC "to avoid the need to recompute the CRC when this field is assigned for every batch that is received by the broker."8 Records inside the batch carry only deltas from the batch's base offset and base timestamp, so setting the base offset fixes the offset of every record in it.8
Compression works on the whole batch because most redundancy is between records, such as repeated JSON field names. The broker decompresses a batch to validate it, then stores it compressed and serves it compressed, and the consumer does the final decompression.1 The codecs are gzip, snappy, lz4 and zstd.8 The broker-side compression.type defaults to producer, meaning "keep whatever codec the producer chose".10, 11
A batch can also be a control batch holding a single control record. Types 0 and 1 are the abort and commit markers of transactions, and the KRaft metadata log uses further types for its own bookkeeping.8 Kafka 4.0 removed the message-format-version settings and the protocol versions that predate this format, so a 4.x broker writes new data only in this layout.5, 12
1.3 Sparse, memory-mapped indexes
To serve "read from offset N" the broker needs a byte position inside a segment. The .index file maps offsets to positions with 8-byte entries: a 4-byte offset relative to the segment's base and a 4-byte file position. The file is preallocated, memory-mapped and never checksummed. After a crash it is rebuilt from the log.13 It is sparse. An entry is added roughly every index.interval.bytes of log, 4,096 by default, so a lookup finds the greatest indexed offset at or below the target and scans forward from there.11, 13 The .timeindex does the same job from timestamp to offset.11
Because the index is mapped, a lookup costs almost nothing when its pages are in the page cache and a blocking page fault when they are not. That makes the search order matter. Almost every lookup, from a caught-up consumer or an in-sync follower, lands near the end of the index, but a textbook binary search also probes the middle of the file. Those midpoints change each time the index grows by a page, and the newly probed pages have often been untouched for a long time. The source comments record what that did: a single cold fault "can cause the at-least-once produce latency to jump to about 1 second from a few ms."14 The fix is to first check whether the target lies in the last 8,192 bytes of the index, the "warm section", and search only there if it does. With default settings that region covers about 4 MB of log, and every lookup that touches it keeps the same few pages hot.14
1.4 Durability without fsync
An append is a write into the page cache. By default no fsync is tied to it. The per-message and per-interval flush settings default to "never", which leaves the work to the kernel's background writeback and Kafka's own background flush, and the documentation recommends keeping it that way.10, 15 The argument has two parts. Calling fsync on every write "can reduce performance by two to three orders of magnitude". And local disks are not the stable storage that textbook protocols assume, because disk errors "often do not leave data intact".1 So Kafka takes its durability from replication: "a failed node will always recover from its replicas."15
What a crash costs is bounded by bookkeeping. A checkpoint file records how far each log is known to be flushed and is updated every 60 seconds by default.10 On restart the broker rereads any segment not known to be flushed, checks the CRC of every batch, cuts the log at the first invalid one, and rebuilds the indexes.2, 15 Whatever the replica lost is fetched again from the current leader, and a replica that crashed must fully resync before it is trusted again.1
The same choice shapes capacity planning. The broker does not cache message data in its heap, so the rest of the machine's memory is the cache. The operations guide suggests sizing memory to hold about 30 seconds of writes.15
1.5 Retention and compaction
Because reading does not consume, something else has to bound the log. The topic's cleanup.policy chooses how: delete (the default), compact, both, or, since 4.2, an empty list that means keep everything.5, 11
Deletion works on whole segments. A segment becomes eligible when its largest record timestamp is older than retention.ms (seven days by default), or when the partition exceeds retention.bytes, which is off by default.2, 7, 10 The granularity is the price of cheapness: a record can outlive its retention time by as long as it takes the rest of its segment to age out. Readers are not blocked by deletion, because the segment list is copy-on-write.2
Compaction is for topics that are a changelog of keyed state, where only the latest value per key matters. It guarantees that the log keeps at least the last record for every key, never reorders records, and never changes an offset.1 A pool of cleaner threads does the work. Each one picks the log with the highest ratio of dirty (never cleaned) bytes to total bytes, provided it is over min.cleanable.dirty.ratio (0.5 by default).7, 16 It scans the dirty section to build a map from key hash to latest offset, at 24 bytes per entry, so an 8 GB buffer covers roughly 366 GB of 1 kB messages. Then it recopies the segments without the records the map says are superseded and swaps the new files in.1, 16 A record with a null value is a tombstone. It deletes the key and is itself removed after delete.retention.ms, 24 hours by default.1, 7 The active segment is never cleaned, so a quiet compacted topic compacts only when a segment rolls.1 The cleaner also stops at the last stable offset (Section 2.5) and drops the records of aborted transactions.16 The internal __consumer_offsets topic is a compacted log.3
1.6 Tiered storage
Keeping all retained data on broker disks ties storage to compute. The proposal that introduced tiered storage (KIP-405) describes the usual workaround of a short retention, typically three days, plus pipelines that copy older data elsewhere. It also names the operational cost: a replacement broker has to copy all the data the failed one held, and a new broker has to copy every partition moved to it.17
Tiered storage splits the log into a local tier, which behaves exactly as described above, and a remote tier such as S3 or HDFS that holds completed segments.18 Topics opt in with remote.storage.enable. They then have two retention settings: local.retention.ms or local.retention.bytes for the broker disk, and retention.ms or retention.bytes for the log as a whole.18
The partition leader copies a segment to the remote tier when the segment is no longer active and ends below the last stable offset, because remote storage "should contain only committed/acked messages."19 A local segment can be deleted only after it has been uploaded.18 Two plugin interfaces sit under this. A RemoteStorageManager moves segment and index files, and Kafka ships no production implementation of it. A RemoteLogMetadataManager records which segments exist remotely, and its default implementation stores that in the internal __remote_log_metadata topic.5, 18
A fetch for an offset that is no longer on local disk is served by the broker from the remote tier.18 The hot path does not change either, because tail reads still come from the page cache and only backfill reads go remote.18 Replication is where the design pays off, because a replacement broker does not need the tiered data on its own disk. From 4.3, with follower.fetch.last.tiered.offset.enable, a follower that starts with no local data skips to the earliest offset not yet uploaded and avoids refetching what remote storage already holds.5 Replacing a broker then costs time proportional to the tail that is still local-only, not to total retention.
Two limits matter in practice. Compacted topics cannot be tiered.18 And until 4.4 every closed segment was uploaded at once, so recent data was stored twice. The new remote.copy.lag.ms and remote.copy.lag.bytes settings let the upload wait.5, 11
Section 2: The Producer Path
2.1 The client picks the partition
There is no routing tier in front of the brokers. Any broker can answer a metadata request saying which brokers are alive and which one leads each partition, and the producer then sends directly to the leader.1 Choosing the partition is the client's job. If a record has a key, the built-in partitioner hashes the serialized key with murmur2 and takes the result modulo the partition count, so all records with one key land in one partition and keep their order.1, 20 The partition count is part of that formula, so adding partitions to a topic changes where existing keys go.
Records without a key are a batching problem. Spreading them one by one over all partitions would produce many small batches. The default logic is sticky instead: it keeps sending to one partition until at least batch.size bytes have gone there and then moves on. By default it also weights the next choice toward partitions on brokers that are responding faster.4
2.2 Accumulate, linger, send
With poor disk access patterns out of the way, the design document names the two remaining sources of waste: "too many small I/O operations, and excessive byte copying."1 The shared batch format handles the copying. Batching in the client handles the small I/O.
send() does no network I/O. It adds the record to an in-memory buffer for its partition and returns, and a background I/O thread turns buffers into requests.21 The buffers are capped in total by buffer.memory (32 MiB). When that is exhausted send() blocks for up to max.block.ms and then fails, which is the producer's backpressure.4 A request to a broker carries one batch for every partition on that broker with data ready to go.4
A batch is ready when it is full (batch.size, 16,384 bytes) or has waited linger.ms. The linger default was 0 for most of Kafka's history and became 5 ms in 4.0, because "the efficiency gains from larger batches typically result in similar or lower producer latency despite the increased linger."4, 5 Fewer, larger requests mean less per-request work on the broker, and under load the queueing saved there can outweigh the wait. Compression is applied per batch, so larger batches also compress better. It is off by default.4
| Producer setting | Default in 4.4.0 | What it controls |
|---|---|---|
acks | all | when the leader may answer a produce request |
enable.idempotence | true | broker-side removal of duplicates caused by retries |
max.in.flight.requests.per.connection | 5 | pipelined requests per broker; at most 5 with idempotence |
delivery.timeout.ms | 120,000 | total time to report success or failure, retries included |
batch.size / linger.ms | 16,384 / 5 | when a batch is considered ready |
buffer.memory / max.block.ms | 32 MiB / 60,000 | client buffering and how long send() may block |
compression.type | none | codec applied to each batch |
All of these come from the producer's configuration definitions, where the retries default is the maximum integer and the advice is to leave it alone and bound retries with delivery.timeout.ms.4
2.3 acks, and what "committed" means
The acks setting decides when a send counts as done. With acks=0 the producer does not wait at all and never learns of failures. With acks=1 the leader answers after writing to its own log, so the record is lost if the leader dies before a follower copies it. With acks=all the leader answers only when "the full set of in-sync replicas" has the record.4
"All" means all replicas currently in sync and not all replicas assigned. A topic with two replicas, one of them down, still accepts acks=all writes with a single copy.1 The floor is the topic setting min.insync.replicas. When the in-sync set is smaller than that, the leader rejects acks=all writes with NotEnoughReplicas before appending anything.11, 22 Its default is 1, which is no floor at all.10 For topics that take part in transactions, the producer documentation recommends a replication factor of at least 3 with min.insync.replicas=2.21 The same pairing is a sensible floor for any topic that must not lose data: it survives one broker failure without losing acknowledged writes and without refusing new ones.
2.4 Idempotence: making retries safe
A produce request that times out tells the producer nothing. The write may have failed, or it may have succeeded with the response lost. Retrying is the only way to be sure the record is written, and before Kafka 0.11 a retry could write the batch twice.1 It could also reorder data. With several requests in flight, an early batch that failed and was retried could land after a later one.4
The idempotent producer closes both gaps with three fields of the batch header. The broker assigns each producer an ID. The producer numbers the batches it sends to each partition with a sequence, and the leader accepts a batch only if its sequence directly follows the last one it appended for that producer ID.1, 8 A lower sequence is a duplicate, and a gap means something was lost. The leader also remembers the metadata of the last five batches per producer. When a retry matches one of them it appends nothing and returns the offsets of the original write.4, 9 That number is why max.in.flight.requests.per.connection may not exceed 5 when idempotence is on.4
This state has to survive a leader change, and it does because it lives in the log itself. Every batch carries its producer ID and sequence, and even compaction keeps the last batch of each producer so the sequence can be recovered. A new leader rebuilds the table from its own copy.8 Idempotence has been on by default since Kafka 3.0.21 Its scope is limited. It removes duplicates created by the client's internal retries within one producer session. A record the application itself sends twice is two records, and the guarantee does not carry over to a restarted producer.21
2.5 Transactions: atomic writes across partitions
Idempotence protects one partition. A stream processor needs more. It reads from an input topic, writes results to output topics, and records how far it has read, and those steps must all take effect or none of them. Kafka can offer this because the consumer's position is itself a record in a topic, so "we can write the offset to Kafka in the same transaction as the output topics receiving the processed data."1
producer.initTransactions(); // registers the id, fences old instances
while (running) {
var batch = consumer.poll(Duration.ofMillis(200));
producer.beginTransaction();
for (var r : batch)
producer.send(new ProducerRecord<>("out", r.key(), process(r.value())));
producer.sendOffsetsToTransaction(nextOffsets(batch),
consumer.groupMetadata());
producer.commitTransaction(); // abortTransaction() on error
}
The helpers process and nextOffsets are the application's. The rest follows the pattern in the client documentation.1, 21 Underneath, the protocol is a two-phase commit with the log as its only storage.
- Identity and fencing. A configured
transactional.idsurvives restarts.initTransactions()registers it with a transaction coordinator, a broker module that keeps its state in an internal transaction log. Registering again makes sure that any transaction left open by a previous instance is aborted and that the old instance is fenced off by a newer producer epoch.1, 4, 23 - Writing. Transactional batches go to ordinary partition leaders with the
isTransactionalbit set. They are appended, replicated and assigned offsets like any other batch.8 - Deciding. On commit the coordinator moves the transaction to
PrepareCommitin its log. That write is the decision. It then has the leader of every partition involved append a commit marker, a control batch, and recordsCompleteCommitonce all of them have acknowledged. Aborting takes the same path with abort markers.1, 8, 23 - Reading. A consumer with
isolation.level=read_committedis served only up to the last stable offset (LSO), the point below which every transaction has been decided. Each fetch response also lists the aborted transactions in the returned range so that the client can drop their records.12, 24 The default isolation level isread_uncommitted, which returns everything.25
Two consequences follow from the mechanism. First, an open transaction holds back the LSO for its partitions, so a stuck transactional producer stalls every read-committed consumer behind it until the coordinator aborts the transaction at transaction.timeout.ms, 60 seconds by default.4, 9 Second, aborted records are not deleted. They remain in the log with their offsets and are filtered out on read.1
Kafka 4.0 hardened the protocol (KIP-890). The producer epoch is now bumped on every transaction, so a delayed write from an earlier transaction cannot be mistaken for part of the next one. Partitions are also added to a transaction by the broker during the produce call, which saves a client round trip.26 The feature is controlled by the transaction.version feature flag and switched on when an upgrade to 4.0 is finalized.5, 26
The guarantee covers reading from Kafka, processing and writing back to Kafka. A side effect in an external system is outside the transaction unless that system stores the consumer's offset together with its output.1
Section 3: Inside the Broker
3.1 Threads and queues
Kafka speaks a size-delimited binary protocol over TCP, and every API is a request and response pair.27 The broker serves it with three kinds of thread. Each listener has one acceptor thread that takes new connections and hands them to N processor threads. Each processor owns a selector and does nothing but read requests off sockets and write responses back. A separate pool of M handler threads executes the requests.28 The defaults are num.network.threads=3 per listener and num.io.threads=8, with a shared queue between them bounded by queued.max.requests=500.29, 30 When that queue is full the network threads block, the broker stops reading sockets, and TCP pushes the pressure back to the clients.29
clients --TCP--> Acceptor --> Processor 0..N-1 one selector each: read a
| request, mute the connection
v
request queue queued.max.requests = 500
|
v
Handler 0..M-1 num.io.threads = 8: validate,
| then append to or read the log
+--------------+--------------+
| |
answer at once park in purgatory (timing wheel)
(acks=0/1; fetch with data) produce waiting for the ISR,
| fetch waiting for bytes
+--------------+--------------+
|
v
Processor response queue --> socket, then unmute the connection
One rule keeps this simple. The broker processes one request per connection at a time. A processor mutes a connection as soon as it has read a complete request and unmutes it only when the response has been sent, so requests on one connection are handled and answered in the order they were sent.27, 28 Clients may still pipeline. Later requests wait in the socket buffer.27 The producer's per-partition ordering depends on this rule. It is also why a slow request delays everything behind it on the same connection.
3.2 Purgatory: waiting without holding a thread
Two common requests cannot be answered when they arrive. A produce request with acks=all must wait until the in-sync followers have fetched the new records. A fetch request at the end of the log must wait for data, because fetch is a long poll: the client supplies a maximum wait and a minimum number of bytes, 500 ms and 1 byte by default for the Java consumer.12, 25 Tying up one of eight handler threads for either would stall the broker.
So the handler does what it can now and parks the rest. A produce handler checks that this broker leads the partition and that the in-sync set is large enough, appends the batches, and registers a delayed operation keyed by partition.22 A fetch handler does the same when too few bytes are available.31 Parked operations are finished by later events. A follower fetch that advances the high watermark (Section 4.3) completes the waiting produce requests, and newly readable data completes the waiting fetches.22, 31 A fetch also completes early if leadership moves, if the reader's epoch is fenced, or if a follower's log has diverged and must be truncated.31
Every parked operation needs a timeout as well, and a busy broker holds a great many of them. Kafka keeps them in hierarchical timing wheels. A wheel is an array of time buckets, so starting and cancelling a timer are O(1), where a priority-queue timer such as java.util.concurrent.DelayQueue pays O(log n) for each.32 Cheap cancellation matters because a delayed request that completes normally never reaches its deadline, and its timer has to be removed.
3.3 The fetch path and zero-copy
A fetch names an offset per partition. How far the broker lets it read depends on who is asking: a follower may read to the end of the leader's log, an ordinary consumer only to the high watermark, and a read-committed consumer only to the last stable offset.31 Within that bound the broker finds the segment and uses the offset index to find a byte position. It does not parse, copy or decompress the batches on the way out.1
The response body is a slice of a file, and on Linux it is sent with the sendfile system call.1 The design document counts what that saves. The conventional path makes four copies with two system calls: disk to page cache, page cache to a user buffer, user buffer to a socket buffer, socket buffer to the NIC. With sendfile the kernel sends page-cache pages to the socket directly.1 Combined with batches that were stored as received, the result is that data is copied into the page cache once on the way in and reused for every consumer. On a cluster whose consumers are caught up "you will see no read activity on the disks whatsoever".1
The optimization has limits. With TLS enabled, sendfile is not used, because encryption happens in user space.1 Brokers that terminate TLS spend more CPU and copy every byte they serve. And a consumer that is far behind reads old segments from disk, the infrequent backfill pattern that tiered storage moves off the broker.18
Two refinements of the fetch API matter at scale. Fetch sessions, added in version 7 of the request, let a client that reads thousands of partitions send only what changed since its previous request.12 A consumer can also be redirected to a follower. It sends its rack ID, a broker-side replica.selector.class picks a replica, and the response names a preferred read replica for the next fetch.12, 24, 33 By default the selector returns the leader.33
Section 4: Replication
4.1 Leaders, followers and the pull model
The unit of replication is the partition. Each partition has one leader and zero or more followers. All writes go to the leader, and a follower's log is identical to the leader's, with the same offsets in the same order, except for the records at the end that have not reached it yet.1 Followers replicate by sending the leader the same fetch request a consumer sends. Pulling lets a follower take whatever has accumulated in one batch.1 It also gives the leader its acknowledgements without a separate message: the offset a follower asks for is the end of that follower's log, and the leader re-evaluates what is committed each time a replica's log end offset changes.22 A broker runs num.replica.fetchers fetcher threads per source broker, one by default.33
4.2 In-sync replicas instead of a majority
A replicated log has to answer one question: how many replicas must hold a record before it is acknowledged, so that whichever replica leads next is certain to have it? The common answer is a majority. With 2f+1 replicas a record commits once f+1 have it, and a new leader is chosen from the most complete of any f+1. The design document grants that approach its main benefit, which is that commit latency follows the fastest replicas.1
Kafka chose differently because of the price. Surviving one failure needs three copies under majority voting and surviving two needs five, and "doing every write five times, with 5x the disk space requirements and 1/5th the throughput, is not very practical for large volume data problems."1 Kafka instead maintains, per partition, the set of replicas that are caught up with the leader, the in-sync replicas (ISR). A record is committed when every member of the ISR has it, and any member may then become leader. With f+1 replicas the partition tolerates f failures.1 The design document names Microsoft's PacificA as the closest published relative.1
The cost is that a commit waits for the slowest in-sync replica, so the system must be able to drop a slow one. A follower is out of sync when it has not caught up to the leader's log end within replica.lag.time.max.ms, 30 seconds by default. The one test covers followers that are stuck and followers that are merely slow.22, 33 A degraded follower can therefore hold up acks=all writes for roughly that long before it is removed.
The ISR is itself replicated state, and it has to be, because it defines who may lead. It is stored in the cluster metadata. A leader that wants to change it sends the proposal to the controller, and until the controller confirms, the leader keeps waiting on the larger of the two sets, which is always the safe side.1, 22
4.3 The high watermark
Each replica tracks its log end offset (LEO), the offset the next record will receive. The leader computes the high watermark (HW) as the smallest LEO in the ISR. Everything below the HW is committed, and consumers are never given anything at or above it, so they cannot read a record that a failover might take away.1, 22
replica.lag.time.max.ms.Followers learn the HW from the leader's fetch responses, so a follower's copy of it trails the leader's.24 Each broker saves its high watermarks to disk every five seconds.33 Four offsets describe a partition at any moment.24, 31
| Offset | Meaning | Who is bounded by it |
|---|---|---|
| Log start offset | first offset still retained | any reader asking for older data |
| Last stable offset (LSO) | below it every transaction is decided | read_committed consumers, the log cleaner, tiered uploads |
| High watermark (HW) | below it the full ISR has the data | all consumers; acks=all responses |
| Log end offset (LEO) | next offset to be written | followers |
4.4 Leader epochs: settling who is right after a failover
After a leader change, replicas can disagree about the records above the high watermark. A follower has to discard its own unconfirmed suffix before it follows the new leader. Early versions truncated to the follower's local HW, and since that value lags, KIP-101 showed that the rule could delete committed records or leave two replicas with different data at the same offset.34
The replacement is the leader epoch, a number the controller assigns and increases every time a partition gets a new leader.35 The leader stamps it into each batch as partitionLeaderEpoch, and every replica keeps a small table of epoch to first offset.8, 35 A follower's fetch request carries the epoch of the last record it holds. If the leader's history disagrees, the response carries a diverging epoch, "the largest epoch and its end offset such that subsequent records are known to diverge", and the follower truncates to that point before continuing.12, 24
new leader B, epoch table: epoch 3 starts at 100, epoch 4 starts at 107
old leader A, local log: ... 106 (e3) 107 (e3) 108 (e3)
107 and 108 were written by A alone
A -> B Fetch { fetchOffset: 109, lastFetchedEpoch: 3, currentLeaderEpoch: 4 }
B -> A divergingEpoch { epoch: 3, endOffset: 107 }
A truncates to 107, fetches from 107, receives B's epoch-4 records
The epoch also fences. Each fetch names the leader epoch the requester believes is current, and a broker that sees a stale one rejects the request, so a replica or client with an outdated view of the partition cannot keep reading from it.12, 31
4.5 Minimum ISR, unclean elections and eligible leader replicas
Because the ISR shrinks under failure, it can shrink to the leader alone, and a record "committed" to a one-member ISR has one copy. min.insync.replicas is the guard. Below it the leader refuses acks=all writes, and the high watermark does not advance at all.11, 22 If every in-sync replica is down, the choice is between waiting for one of them to return and electing whichever replica is alive, at the cost of the records it never received. Kafka waits unless unclean.leader.election.enable is set, and it is off by default.1, 7
That left one hole, the "last replica standing" case described in KIP-966. The ISR shrinks to a single broker, that broker crashes before its page cache is flushed, and it returns as the only electable replica with committed records missing.36 Eligible leader replicas (ELR) close the hole by using the frozen high watermark. A record commits only while the ISR is at least the minimum size. The replicas that drop out as the ISR falls below that size, and any that drop out later, therefore still hold every committed record. The controller remembers them as the ELR and removes any that went through an unclean shutdown.37, 38 At election time it picks from the ISR if it can, then from unfenced ELR members, then the last known leader.37
ELR arrived in 4.0 and is enabled by default on clusters created with 4.1 or later. Older clusters turn it on with the feature flag eligible.leader.replicas.version=1.5, 37 It changes how min.insync.replicas is managed: the setting must exist at cluster level, broker-level overrides are removed, and changing it for a topic clears that topic's ELR state.37
Section 5: The Controller and KRaft
5.1 Why ZooKeeper went away
Something has to decide which brokers are alive, who leads each partition and what each ISR contains. Before 4.0 that metadata lived in ZooKeeper, and one broker, elected through ZooKeeper, acted as controller. KIP-500 objected that this made two systems responsible for one state. A newly elected controller had to load its state from ZooKeeper before it could act, its view could drift from what ZooKeeper held, and brokers learned of changes through pushed notifications.39 The proposal was to keep the metadata as a log managed by a Raft quorum of controllers and to let brokers consume that log.39 Kafka 4.0 finished the job by removing ZooKeeper mode. A cluster still on ZooKeeper has to migrate through the 3.9 bridge release first.5, 40
5.2 Metadata as a replicated log
Each server's process.roles says whether it is a broker, a controller, or both.40 The controllers, usually three or five, replicate a single-partition log named __cluster_metadata.40 Whichever controller leads that log is the active controller. The others are hot standbys that replay every record as it arrives, so a failover does not start with a reload of the cluster state.40, 41
The active controller is deliberately simple inside. A single event-handler thread performs almost every operation, which removes the need for complex locking, and the future returned for an operation completes only when its records are durable in the metadata log.41 Topic creation, a leader change, an ISR change, a broker registration and a configuration change are all records. A partition's entry holds its replicas, ISR, leader, leader epoch and partition epoch.40
Brokers do not vote. They are observers of the same log: they fetch it from the active controller and apply it to an in-memory image.40, 42 Every node therefore learns of a change by replaying the same records in the same order. Because the log would otherwise grow without bound, nodes write snapshots of the state, and a replica that has fallen behind the start of the log fetches a snapshot before it resumes fetching records.40, 42
5.3 How KRaft differs from textbook Raft
The implementation describes itself as "a Kafkaesque version of the Raft protocol": leader election "is more or less pure Raft, but replication is driven by replica fetching", and logs are reconciled after an election with the fetch-based truncation of Section 4.4.42 Pull replication needs one addition. A Raft leader normally announces itself by pushing an empty append, which a pull-based leader cannot do, so KRaft has a BeginQuorumEpoch request for that purpose.42
The metadata log differs from data partitions in two ways. It commits by majority, with no ISR. And it uses fsync: the leader flushes its log, and a voter flushes what it has appended before its next fetch can count as an acknowledgement.42 A majority quorum has nothing larger to resync from, so a voter that forgets acknowledged records can break the protocol. For the same reason storage directories must be formatted explicitly with kafka-storage.sh and are never created empty on demand: if a majority of controllers started with empty logs, "a leader might be able to be elected with missing committed data."40
5.4 Broker liveness and leader election
A broker registers with the controller and then sends a heartbeat every two seconds. If none arrives for broker.session.timeout.ms, nine seconds by default, the controller fences the broker.1, 43 Heartbeats are not written to the metadata log. They are soft state held only by the active controller, which keeps the log small, at the price that a newly elected controller may take a little longer to fence a dead broker.44
When a broker is fenced the controller chooses a new leader for every partition it led, from the ISR or failing that the ELR, and writes the changes as records. Deciding in one place and batching the notifications is what makes losing a broker with thousands of partitions cheap.1, 37
5.5 Running the quorum
# controller.properties
process.roles=controller
node.id=1
listeners=CONTROLLER://c1:9093
controller.listener.names=CONTROLLER
controller.quorum.bootstrap.servers=c1:9093,c2:9093,c3:9093
$ bin/kafka-storage.sh format --cluster-id <CLUSTER_ID> --standalone \
--config config/controller.properties
$ bin/kafka-metadata-quorum.sh --bootstrap-server localhost:9092 \
describe --status
$ bin/kafka-features.sh --bootstrap-server localhost:9092 \
upgrade --release-version 4.4
The operational guidance is short. Run controllers on dedicated nodes, since combined broker and controller mode is for development. Run 2N+1 of them to survive N failures, and expect each to need about 5 GB of memory and 5 GB of disk for a typical cluster.40 Quorum membership is dynamic in current versions. A cluster formatted with --standalone or --initial-controllers can add and remove controllers with kafka-metadata-quorum.sh. Kafka 4.1 added an upgrade path from the older static controller.quorum.voters configuration, and 4.4 added a way to unregister a removed controller.5, 40
Upgrades have two steps for a reason. Rolling the binaries changes the code. A separate kafka-features.sh upgrade finalizes the new metadata.version and the related feature levels, and new record formats and protocols stay off until then.5, 41 The consumer protocol, the transaction protocol, share groups and ELR are each gated by such a feature level.5, 26, 37, 45
Section 6: Consumers, Groups and Queues
6.1 Positions, commits and the coordinator
A consumer is a loop of fetch requests plus one number per partition. To survive a restart it commits that number to the group coordinator, the broker that leads the partition of __consumer_offsets (50 partitions by default) to which the group's name maps.3, 46 The coordinator appends the commit to that compacted topic, answers once it is replicated, and keeps a table in memory for lookups.3 Kafka 4.0 shipped a rewritten coordinator. Each offsets partition a broker leads is a replicated state machine driven by an event loop that never runs two operations for the same partition at once, and the response to a write is held back until its records are committed.5, 47
Delivery semantics follow from the order of two steps. Processing a record and then committing gives at-least-once delivery. Committing first gives at-most-once.1 The Java consumer commits automatically every five seconds unless told otherwise.25
6.2 The classic rebalance protocol
Within a consumer group each partition is read by exactly one member.1 A rebalance recomputes that mapping when members come and go. In the classic protocol the coordinator tracks membership, and one of the clients computes the assignment. Members send JoinGroup. The coordinator parks those requests "until all expected members have joined", then waits for the member acting as leader to send the assignment back in SyncGroup. While that is going on, every heartbeat is answered with REBALANCE_IN_PROGRESS, which tells the member to rejoin.48
In the eager variant a consumer revokes all of its partitions before rejoining, so the whole group stops. Cooperative assignors let members keep what they own and move only the difference, in a second round.49 Both variants keep what KIP-848 calls a group-wide synchronization barrier. Every member must arrive before anyone proceeds, so one misbehaving consumer can disturb or take down the whole group.50 Liveness is judged by the client's own settings. Heartbeats must arrive within session.timeout.ms (45 s), and the application must call poll() within max.poll.interval.ms (five minutes).25 Static membership, a fixed group.instance.id, lets a member restart without causing a rebalance.1
6.3 The consumer protocol (KIP-848)
The new protocol moves the assignment into the coordinator and replaces the join and sync exchange with one request, ConsumerGroupHeartbeat.45, 51 A heartbeat carries the member's epoch (0 to join, -1 to leave), its subscription and the partitions it currently owns. Fields that have not changed are sent as null, and the coordinator answers with the member's assignment.51, 52
The coordinator computes a target assignment with a server-side assignor, uniform by default or range.45 It then reconciles each member on its own. A member that has to give up partitions stays at its current epoch until a heartbeat shows they are gone. A member waiting for partitions that someone else still holds advances to the new epoch and receives them as they are released. Everyone else is stable.52 There is no barrier. A consumer whose assignment did not change is not affected at all, and a slow member delays only the partitions it holds.45, 50
| Classic | Consumer (KIP-848) | |
|---|---|---|
| Assignment computed by | one member, with a client-side assignor | the group coordinator, with a server-side assignor |
| Requests | JoinGroup, SyncGroup, Heartbeat | ConsumerGroupHeartbeat |
| A member joins or leaves | all members rejoin at a barrier | only members whose partitions move take part |
| Heartbeat and session timeouts | client configuration | broker configuration (group.consumer.*) |
| Status in 4.4.0 | client default | opt-in with group.protocol=consumer |
The broker side has been generally available since 4.0, with a 5 s heartbeat interval and a 45 s session timeout set on the broker.45, 46 Since 4.3 the coordinator recomputes a group's target assignment at most once a second by default, which batches bursts of membership changes.5 The client default is still classic in 4.4.0. The documented plan is to switch the default in 5.0 and to drop classic support from the Java consumer in 6.0.25, 45 A group converts online as its members are rolled onto the new protocol. The main limitation is that custom client-side assignors are not supported.45
6.4 Share groups: queue semantics on the same log
Consumer groups cap parallelism at the number of partitions and let one slow record block everything behind it in its partition. Share groups (KIP-932), production-ready since 4.2, drop the exclusivity. A partition can be assigned to several consumers, the group can have more consumers than partitions, records are acknowledged individually, and delivery attempts are counted.1, 5
Nothing about the log changes. The broker keeps extra state for each share group and partition: a window of in-flight records between a share-partition start offset (SPSO) and end offset (SPEO).53
offset ... 40 41 42 43 44 45 46 47 48 ...
state done | acq ack acq avl ack acq | not yet fetched by this group
^ ^
SPSO SPEO
acq = acquired by a consumer under a time lock
avl = available for delivery or redelivery
ack = acknowledged; SPSO moves past it once everything before it is finished
A fetch acquires available records for one consumer under a lock, 30 seconds by default. The consumer then acknowledges each record, releases it for another attempt, rejects it as unprocessable, or renews the lock. If it does nothing the lock expires and the record becomes available again.1 The broker limits how many records per partition may be acquired at once, which bounds the window.1 The state is persisted by a share coordinator in the internal __share_group_state topic.5, 53 From 4.4, records that are rejected or exceed their delivery limit can be routed to a dead-letter topic.5
What is given up is ordering. The upgrade notes say to use share groups "in cases where records are processed one at a time, rather than as part of an ordered stream."5
Trade-offs: Kafka and Its Neighbours
Kafka's design is a handful of bets: a log per partition on local disks, replication through an in-sync set without fsync, clients that know the cluster's topology, and metadata in its own quorum. Each neighbouring system changes at least one of them.
Redpanda: the same protocol on a different engine
Redpanda implements the Kafka protocol in C++, without the JVM or ZooKeeper, on a thread-per-core model with asynchronous code throughout.54 Its replication is built on Raft. In quorum mode a write is acknowledged when a majority of replicas have it and have flushed it, according to a 2022 design document in its repository, which contrasts this with a leader-ack mode equivalent to Kafka's acks=1.55 Durability then rests on disks as well as on replica count, and every acknowledged write pays for a flush. One caveat for adopters: as of 12 November 2026 the public repository is marked archived and read-only, and its README says the Community Edition is now under a Redpanda Community Edition License.56 Check the licence before planning around it.
Pulsar: brokers without storage
A Pulsar broker is stateless. Messages are stored in Apache BookKeeper on separate nodes called bookies, and a metadata store, Oxia or ZooKeeper, coordinates the cluster.57 A topic's data is a sequence of ledgers, each an append-only structure with a single writer whose entries are replicated to multiple bookies, so adding bookies adds capacity immediately.57 A new Kafka broker holds nothing until partitions are reassigned to it and their data copied.17 Pulsar also builds queue semantics into its subscriptions. There are four subscription types, and shared subscriptions acknowledge messages individually.58 The price is three cooperating systems to run.
RabbitMQ: queues first
RabbitMQ starts from the queue and has grown toward the log. Its quorum queues replicate with Raft, commit by majority, and count redeliveries to deal with poison messages.59 Its streams add what queues lack, an append-only replicated log that many consumers can read repeatedly from an offset.60 Kafka's share groups are the same convergence from the other side. The choice comes down to which half is the workload: exchange routing and per-message handling, or partitioned high-volume streams with replay.
Diskless designs: object storage as the log
In a public cloud, replication across zones is billed as network traffic and stateful brokers are slow to scale. AutoMQ, a fork of Apache Kafka built on that argument, replaces the storage layer with object storage fronted by a write-ahead log, which makes brokers stateless.61 Aiven's Inkless, a fork that implements the diskless topics proposed for Kafka itself in KIP-1150, goes further.62 A broker packs produce requests from many partitions into one object, writes it to object storage without assigning offsets, and then commits the batch coordinates to a coordinator (a SQL database in Inkless) that fixes the order. No broker keeps a partition's data on its own disk, and each broker caches recently used objects in memory.63 Its diskless topics do not yet support compaction or transactional writes.64 KIP-1150 passed its vote in March 2026, with the core mechanics left to follow-up KIPs, and diskless topics are not among the features of the 4.4.0 release.6, 65
| System | Where the log lives | When a write is acknowledged | Fits when |
|---|---|---|---|
| Apache Kafka 4.4 | segment files on broker disks, optional remote tier | every in-sync replica has it; no fsync by default | high-volume streams, replay, a large ecosystem |
| Redpanda | broker disks, C++ thread-per-core engine | a Raft majority has flushed it | Kafka API with flush-on-ack durability, if the licence suits |
| Pulsar | BookKeeper ledgers; brokers stateless | entries are replicated to multiple bookies | storage must scale apart from serving; mixed queue and stream use |
| RabbitMQ | quorum queues and streams on broker disks | a majority of queue members agree | routing and per-message work queues at moderate volume |
| Diskless Kafka variants | objects in cloud storage | the object is stored and its batches are committed to a coordinator | cloud cost dominates and extra write latency is acceptable |
The last column is this paper's judgement. The others summarize the sources cited above.
Conclusion: The Mental Model to Keep
Kafka is one data structure used many times. A partition is an append-only file of batches, addressed by offset, written once in the producer's format and served from the page cache with sendfile. It is durable because a set of in-sync replicas holds it and not because any disk was flushed, and the high watermark marks what that set has agreed on. Leader epochs repair logs after a failover. The controller, the group coordinator and the transaction coordinator are state machines whose state is another log. A consumer is a cursor, a consumer group divides partitions among cursors, and a share group adds per-record state on top.
Some practical consequences:
- Use a replication factor of 3 with
min.insync.replicas=2, keepacks=alland leave unclean election off. Put replicas in separate failure domains, because writes are not fsynced by default. - Protect batching. Keep a non-zero
linger.ms, turn on compression, and remember that keys are tied to the partition count. - Give the page cache memory. Lagging consumers and TLS both take the fast path away.
- Run three or five dedicated controllers. Finalize feature levels after an upgrade, and check that ELR is enabled on clusters created before 4.1.
- Move consumers to
group.protocol=consumerwhen their clients support it, and use share groups for work-queue jobs where order does not matter. - Use tiered storage when retention, not throughput, is what sizes your brokers.
Kafka is a poor fit in a few cases. One is a low-volume task queue that needs routing rules, priorities or per-message delays, where a queue broker is simpler. Another is request and reply messaging. A third is any deployment that cannot run at least three brokers or needs each write on stable storage before it is acknowledged. Large payloads are a fourth, since the default batch limit is about 1 MiB.10 And where object-storage economics decide the design, the diskless variants are worth a look. Kafka itself fits when the problem is a log: many writers, many independent readers, and a need to read the same data again.