Kafka internals

Part of the free LogicWiz Data Engineering course, Module 15: Streaming. The SQL and Python run in the app, on real Postgres and real Python in the browser.

At 02:14 on Saturday, broker 1 lost power. A minute later the cluster looked healthy: broker 2 led every partition that broker 1 had led, and nothing was offline. On Monday Tess found 37 payments that checkout had been told were saved, and that never reached the warehouse. Nobody deleted anything, and no broker logged an error. Nora says: "Kafka did exactly what we asked. Find out what we asked for."

You'll learn to

  • Trace a record through segment files, the index and the page cache
  • Explain leader, in-sync replicas, the high watermark and acks
  • Predict what a broker failure loses under each setting
  • Say what unclean election, the cleaner and KRaft do

Learn

Follow one payment to the disk

Dana's checkout service sends a payment to the payments topic and gets an answer: saved, at an offset. Where is it now?

On a broker's disk a partition is a plain folder, payments-0/. The log inside is cut into files called segments. Only the newest, the active segment, takes new records. At 1 GiB, or after 7 days, Kafka closes it and starts a new one.

A segment is named after the offset of its first record, its base offset, padded with zeros to 20 digits. It is three files:

  • .log: the records, in the batches the producer sent
  • .index: a short list that maps an offset to a position in the .log
  • .timeindex: the same, for timestamps

Old data is removed by deleting whole closed segments, so no record is ever rewritten.

Inside payments-0/

A folder tree for one partition: a closed 1 GiB segment and the active segment, each with log, index and time index files, plus a producer state snapshot, the leader epoch checkpoint and the partition metadata file.

Read the file names as offsets. With 256-byte records on disk, a full 1 GiB segment holds 2^30 / 256 = 4,194,304 records, so the next segment's base offset is 4194304. The last three files come back later in the lesson.

Finding one offset among millions

You ask broker 2 for the offsets checkout wrote down. It answers in milliseconds: they do not exist. How can it be sure so fast? Take offset 5,000,009.

  1. Pick the segment. The broker keeps the base offsets in memory and searches them by halving (a binary search). 4,194,304 is the largest base offset not above the target.
  2. Look in the index. The .index does not list every record. It has one entry for about every 4,096 bytes of log: it is sparse. The broker finds the last entry not above the target, which gives a position in the .log.
  3. Scan forward a few records to the exact one.

Think of a dictionary. The words printed at the top of each page get you to the right page, and then you read down.

Model the lookup with two searches

import bisect

segments = [0, 4_194_304, 8_388_608]   # base offsets of three segments
RECORD = 256                            # bytes per record on disk
INTERVAL = 4096                         # index.interval.bytes

def segment_for(offset):
    """The segment holding offset: the largest base offset not above it."""
    return segments[bisect.bisect_right(segments, offset) - 1]

def build_index(records):
    """A sparse index: one (relative offset, byte position) entry per 4 KB of log."""
    every = INTERVAL // RECORD
    return [(r, r * RECORD) for r in range(0, records, every)]

target = 5_000_009
base = segment_for(target)
index = build_index(4_194_304)
rel = target - base
i = bisect.bisect_right([r for r, _ in index], rel) - 1
entry, position = index[i]
print('segment', f'{base:020d}.log')
print('index entries', len(index), '- entry', i, 'points to byte', position)
print('records to scan from there:', rel - entry)

A full 1 GiB segment has 2^30 / 4,096 = 262,144 index entries. The search lands on entry 50,356 and 9 records are scanned from there. Two searches and a short scan, however big the partition: what costs time is whether the bytes are in memory.

Written does not mean on disk

Here is the first surprise. When a broker says "written", the bytes are in the operating system's memory, the page cache. They are not on the disk yet. Kafka lets the operating system write them out later, and by default never forces a disk write per message.

So one broker that loses power can lose its newest records. Kafka's safety does not come from the disk. It comes from copies on other brokers.

The same choice makes Kafka fast. Readers near the end of the log are served straight from the page cache. And the broker sends those bytes to the network without copying them through its own program, a trick called zero-copy (sendfile). With TLS it cannot, because encryption happens inside the program, so TLS brokers spend more CPU per byte.

Serving a fetch

Segment files are paged into the OS page cache; with plain connections sendfile moves bytes from the cache to the network card directly, while with TLS they are copied into the JVM heap to be encrypted first.

Follow the teal arrows: disk, memory, network, with no detour. So size the page cache for the tail you serve: at 20 MB/s with 3 replicas on 3 brokers, each broker writes 20 MB/s, and 10 minutes of tail is 20 x 600 = 12 GB of RAM per broker, outside the JVM. A reader that goes back to old segments forces disk reads, and pushes the recent data out of the cache for everyone else.

Three copies and a high watermark

Each partition has copies on several brokers, usually 3. These are its replicas. One is the leader: it takes every write. The others are followers: they keep asking the leader for new records, exactly as a consumer would.

A follower that keeps up is in sync. The set of in-sync replicas is the ISR. A follower that has not caught up for 30 seconds is dropped from it.

Now the key idea. Each replica's log ends somewhere: its log end offset (LEO). The smallest LEO in the ISR is the high watermark (HW). Everything below it is on every in-sync replica, so it is committed, and consumers only ever read below it. (It has nothing to do with the event-time watermark of Lesson 15.4.)

How one payment becomes committed

A producer and three brokers: the leader appends a payment at offset 100, both followers fetch and copy it, their next fetch tells the leader they have it, the high watermark moves to 101, and only then is the producer answered.

  1. The payment arrives. The leader appends it at offset 100, so its log now ends at 101. The followers do not have it yet, so the high watermark stays at 100.

  2. The followers fetch. Each asks the leader for records from offset 100 on, and copies the payment.

  3. The followers report. Their next fetch asks for offset 101, which tells the leader they hold 100. The smallest LEO in the ISR is now 101, so the leader moves the high watermark to 101. The payment is committed.

  4. The leader answers. A producer that asked to wait for every in-sync replica hears "saved" only now. Remember where the high watermark stood in step 1: you will need it in a moment.

Read the line under each broker: LEO is where its log ends, HW is how far every in-sync copy has got.

What "saved" meant at 02:14

So when does a producer hear "saved"? That is the producer's own choice, a setting called acks:

  • acks=0: do not wait at all. Send and hope.
  • acks=1: as soon as the leader has written it.
  • acks=all: once the record is below the high watermark, on every in-sync replica.

You open the config of the payments producers. It says acks=1.

Put that next to the last two sections. With acks=1, "saved" means "in the memory of one broker". Step through what that meant on Saturday night.

02:14: the leader dies holding the only copy

A producer with acks=1 and three brokers: the leader acknowledges a payment before the followers copy it, loses power, broker 2 becomes leader without the payment, and the old leader truncates its log when it returns.

  1. A payment arrives, with acks=1. Broker 1 appends it at offset 100 and answers at once. Checkout tells the shopper the payment is saved. The followers have not fetched it yet.

  2. Broker 1 loses power. The only copy of offset 100 was on that machine, and perhaps only in its memory.

  3. A new leader. Broker 2 is in the ISR, so it is chosen. Its log ends at offset 99. The cluster looks healthy again, and the next payment to arrive will be given offset 100.

  4. Broker 1 comes back. It holds a record the new leader never had, so it cuts its log back to match: it truncates. The payment is now on no broker at all. Thirty-seven payments went this way.

Same four boxes as the last picture. The only difference is step 1: the answer left before the followers had the record. Broker 1 knows where to cut from the leader-epoch-checkpoint file you saw in the folder.

Kill the leader with acks=1 and with acks=all

import ministream as ms

for acks in ['1', 'all']:
    log = ms.ReplicatedLog(replicas=3, min_insync=2)
    log.produce('p1', acks=acks)
    log.fetch()                                    # p1 is on all three brokers
    print(f'acks={acks}: p2 ->', log.produce('p2', acks=acks))
    log.kill(1)                                    # the leader dies before the followers fetch
    print('   leader now', log.leader, '| hw', log.hw, '| lost', log.lost(), '| still waiting', log.pending)

log = ms.ReplicatedLog(replicas=3, min_insync=2)
log.kill(3)
log.kill(2)                                        # two brokers down: the ISR is the leader alone
print(log, log.produce('p3', acks='all'))

With acks=1, p2 was acknowledged and is gone. With acks=all it was never acknowledged, so the producer retries it on the new leader. The last line is two brokers down: min.insync.replicas=2 refuses the write rather than keep one copy. That setting is next.

One partition on three brokers with leader, followers, in-sync replicas, log end offsets and the high watermark; the producer sends with acks 0, 1 or all while a follower stalls and the leader dies.

Step through with acks=all, then switch to acks=1: at step 9 the leader dies holding m5, which acks=1 had already acknowledged.

The two settings that would have saved them

The first fix is plain: acks=all. The producer then hears "saved" only when the payment is below the high watermark.

It is not enough alone. acks=all waits for the replicas that are in sync, and that set can shrink. If both followers fall behind, the ISR is the leader alone, and "all" means one.

The second setting stops that: min.insync.replicas. With acks=all, if fewer replicas than this are in sync, the leader refuses the write with NotEnoughReplicasException. Its default is 1, which protects nothing.

The usual choice for business data is 3 replicas, min.insync.replicas=2 and acks=all. One broker can fail with no loss and no stop to writes. The price: with two brokers down, writes stop. You give up a little availability so that "saved" is never a lie.

What each setting can lose (replication factor 3)

SettingsAn acknowledged write is lost whenWrites stop when
acks=0any failure, and the producer never knowsthe partition has no leader
acks=1the leader dies before a follower has copied itthe partition has no leader
acks=all, min.insync.replicas=1the ISR has shrunk to the leader alone and it dies, or an unclean electionthe partition has no leader
acks=all, min.insync.replicas=2both in-sync copies are lost, or an unclean electiontwo brokers are down: one down still writes
acks=all, min.insync.replicas=3as aboveany one broker is down

Read down the middle column: each row closes one more way to lose data. The fourth row is the usual choice. (Unclean election is the next section.)

Remember: the high watermark is the smallest log end offset in the ISR. acks=all means "all in-sync replicas", not "all replicas", so it is only as strong as min.insync.replicas.

When no in-sync copy is left

One more door has to stay shut. Suppose the leader dies and no in-sync replica is alive. Who leads now?

unclean.leader.election.enable decides, and its default is false: the partition stays offline until an in-sync replica returns. Nothing is lost, but nobody can write.

Set it to true and an out-of-sync replica may lead at once. Whatever it lacks is gone, even if it was acknowledged, because the other replicas truncate to match it when they return.

Kafka 4.0 added a safer middle path, Eligible Leader Replicas (KIP-966): a preview in 4.0, on by default for new clusters since 4.1. The high watermark cannot move while the ISR is smaller than min.insync.replicas. So a replica that dropped out of the ISR at such a time still holds every committed record, and may be elected cleanly.

Brokers fail one by one until the last in-sync replica dies and the partition goes offline; with unclean leader election on, an out-of-sync broker becomes leader and acknowledged messages are lost.

Run it with the defaults, then turn unclean election on: the partition is back sooner and m3 and m4 are gone. With min.insync.replicas=2, m4 is refused instead of acknowledged on one disk.

What else lives in the log

Two things from Lesson 15.3 are stored right here, in the partition.

The producer's sequence numbers. The leader keeps them in memory, and writes them to the .snapshot file each time a segment is closed. A restarted broker rebuilds them from the last snapshot plus the log after it, so it still spots a retried duplicate.

Transaction markers. A commit or an abort is a small control record in every partition the transaction touched. It takes an offset, and it is never handed to your code.

One more thing works on the log from behind: the cleaner, which does the compaction of Lesson 15.2. It never touches the active segment. It copies the older segments, leaving out every record whose key has a newer value.

A compacted partition before and after cleaning

OffsetKeyValueAfter the cleaner runs
018Munichremoved: key 18 has a newer value
16Torontoremoved: key 6 has a newer value
218Berlinremoved
36null (a tombstone)kept until delete.retention.ms (1 day) has passed
47Lagoskept: the newer value is in the active segment
518Pariskept: the newest value of 18
67Accraactive segment: not cleaned, not even read

Offsets never change. The cleaner (log.cleaner.threads, 1) picks the log with the largest uncleaned share above min.cleanable.dirty.ratio (0.5), maps each key to its newest offset in log.cleaner.dedupe.buffer.size (128 MiB), and recopies the segments without the superseded records.

Who decided that broker 2 leads?

One question from the night is left. Who chose broker 2?

Something must hold the cluster's own facts: which brokers exist, who leads each partition, who is in each ISR. Since Kafka 4.0 that is always KRaft: a small group of servers called controllers. They keep these facts in a log of their own, __cluster_metadata, and agree on it by majority vote (the Raft protocol).

One controller is active. The others are hot standbys that already hold the log in memory, so when the active one dies a standby takes over without reloading anything. Brokers read the metadata log the way followers do.

Decisions need a majority, so run 3 controllers to survive one failure, or 5 to survive two: 2N + 1.

A KRaft cluster

Three controllers, one active and two standbys, replicate the cluster metadata log; three brokers fetch that log to learn partition leaders and in-sync replicas, and hold the topic partitions.

Top row: the three controllers that vote. Bottom row: the brokers that hold your data and follow what the controllers decide.

Replication factor 3 is not durability on its own. min.insync.replicas defaults to 1, so with acks=all the leader can acknowledge a write only it holds, once the followers have left the ISR. Set min.insync.replicas=2 on business topics, keep acks=all, and never enable unclean election for them. Hunt for acks=1 in old client configs: it also silently turns idempotence off.

Numbers to remember

SettingDefaultWhat it does
segment.bytes, segment.ms1 GiB, 7 dayswhen the active segment is closed and a new one starts
index.interval.bytes4,096one index entry per this many bytes of log; the index file is memory-mapped
.timeindextimestamp to offsetfor seeking by time, as Spark's startingOffsetsByTimestamp does
log.flush.interval.messageseffectively unlimitedno forced disk write per message: durability comes from replication
batch.size, linger.ms16 KB, 5 ms since Kafka 4.0 (0 before)the producer groups records per partition, compresses the whole batch, and the broker stores and serves it as it came
Batching, worked833 records of 1 KB a second per partition5 ms gathers about 4 records (4 KB); with 20 ms the 16 KB batch fills first, after about 19 ms
replica.lag.time.max.ms30 sa follower behind for longer leaves the ISR
min.insync.replicas1applies only to acks=all; set 2 on business topics
unclean.leader.election.enablefalsewhether an out-of-sync replica may lead
transactionstatereplication factor 3, min.insync.replicas 2the transaction coordinator's log; aborted transactions are listed in a per-segment .txnindex, so a readcommitted fetch knows what to skip
KRaftthe only mode since Kafka 4.0ZooKeeper clusters must migrate on a bridge release (3.9 is the last) before upgrading; controllers run on their own servers in production
Changing the controller quorumsince 3.9 (KIP-853)new setups list controller.quorum.bootstrap.servers instead of the static controller.quorum.voters
Alerts to setUnderReplicatedPartitions, UnderMinIsrPartitionCount, OfflinePartitionsCounta follower behind; acks=all writes failing; no leader. Spread replicas over zones with broker.rack

What changed at SwiftKart

The payments producers move to acks=all. The topic gets min.insync.replicas=2, and unclean election stays off. You audit every other topic for the same settings, and add alerts for partitions that are under-replicated or below their minimum.

Then you test it: you stop one broker of a test cluster on purpose. Writes carry on, and every acknowledged payment is on the two brokers left.

The 37 payments are recovered from the bank's records and loaded by hand, once.

Kafka now keeps the promise you meant. The last lesson of the module goes to the other end of the pipe: the Spark job that reads these topics, and the one folder that holds everything it remembers.

In one line

Kafka keeps a partition as segment files served from memory, and a record is safe only once every in-sync copy has it: use acks=all with min.insync.replicas=2, and keep unclean election off.

Interview corner

Walk me through a produce with acks=all.

The producer sends a batch to the partition leader, which appends it to the active segment in the page cache, so its log end offset moves but the high watermark does not. Followers fetch from the leader, copy the batch, and their next fetch carries their new log end offset. When every replica in the ISR has it, the leader advances the high watermark, the batch becomes committed and visible to consumers, and only then is the producer acknowledged. If the ISR is smaller than min.insync.replicas, the write is refused with NotEnoughReplicasException.

When can Kafka lose a message the producer was told was saved?

With acks=1, if the leader dies before a follower copies the record; with acks=0 at any time. With acks=all and the default min.insync.replicas=1, when the ISR has shrunk to the leader alone and that broker dies, and with unclean leader election, when an out-of-sync replica becomes leader and the others truncate to it. Replication factor 3, min.insync.replicas=2, acks=all and unclean election off close those gaps for a single failure.

Why is Kafka fast, and when is it slower than you expect?

Appends are sequential, the OS page cache holds the recent tail so consumers read from memory, sendfile moves bytes from that cache to the socket without copying into the JVM, and producers send compressed batches that the broker stores unchanged. It gets slower when TLS is on, because zero-copy is not possible, when a backfill reads cold segments from disk and evicts the hot tail, and when batches are tiny because linger.ms is low or there are too many partitions per producer.

What changed with KRaft, and why does it matter to you?

Since Kafka 4.0 there is no ZooKeeper: a quorum of controllers, usually 3 or 5, replicates the cluster metadata in the __cluster_metadata log with Raft, and brokers fetch it. Standby controllers already hold the metadata in memory, so a controller failover does not reload state. Operationally it means one system to run, controllers sized by 2N + 1, migrations from ZooKeeper only through a 3.9 bridge release, and new features such as eligible leader replicas that assume KRaft.