Data · L2Kafka internals

Kafka internals

Kafka is a set of logs on disk, copied between brokers. Learn which settings decide what is safe, what is ordered, and what pauses.

L2 SeniorData20 min read
Fact-checked by AI against cited sources · Human review pendingLast reviewed 13 Nov 2026 · How we check content
Section 1 of 8

What broke

In September 2013, Kyle Kingsbury tested a pre-release of Kafka 0.8 with his tool, Jepsen. His question was simple: when Kafka says a write is safe, is it? 1

Kafka keeps each partition on several servers, called brokers. One copy is the leader. The leader tracks which followers are up to date: the in-sync replicas, or ISR. A write counted as committed once every member of the ISR had it. 1

He cut the leader off from its followers. They timed out and dropped out of the ISR, so the leader was alone in it. It kept acking writes that existed only on its own disk. The producer was waiting for every in-sync copy, and it still got "ok". 1

Then the leader lost its claim, and Kafka elected a follower that was far behind. When the old leader came back, its writes conflicted with the new leader's log and were thrown away. Of 987 acked writes, 520 were lost. 1

He suggested that Kafka should "block and sound an alarm" instead of silently dropping data. 1 Kafka later changed its default. Since version 0.11.0.0, it waits for an in-sync replica rather than elect one that is behind. 3 2 But two settings still decide whether your writes are safe. Most teams never look at them.

Section 2 of 8

The idea in simple words

You know from queues vs logs that a Kafka topic is split into partitions. Each partition is a log: messages are only added at the end, and each gets an offset.

This lesson shows what is inside. A partition is a set of files on a broker's disk. It is copied to other brokers. A producer picks the partition for each message. A consumer group splits the partitions among its members, and each member saves its offset.

The key idea. Kafka gives every guarantee per partition: the order, the leader, the copies and the consumer's offset. Once you see that, most Kafka behaviour makes sense.

Section 3 of 8

How it works

Segments on disk

A partition is not one big file. It is a series of log segments. Each segment file is named after the offset of its first message, like 00000000000000000000.log. New messages go to the newest segment. When it reaches a size limit, Kafka starts a new one. 4 That limit is segment.bytes, 1 GiB by default. Kafka also rolls a segment after segment.ms, 7 days by default. 5

To read from an offset, Kafka first finds the segment that holds it, then the position inside the file. 4 Next to each segment, an index maps offsets to file positions. Kafka adds an entry about every 4 KiB of data (index.interval.bytes). A second index, the time index, gets entries on the same schedule when the timestamp has moved forward. It lets Kafka find messages by time. 5

Kafka writes to the file system and leans on the OS page cache. It writes to the log without necessarily flushing each write to disk. 3 Its safety comes from copies on other brokers, not from one disk.

Retention and log compaction

With the default cleanup.policy=delete, Kafka keeps data for retention.ms, 7 days by default. A size limit, retention.bytes, is off by default. 5 Kafka deletes old data one whole segment at a time. 4 So data can live a bit longer than the limit, until its segment is old enough.

With cleanup.policy=compact, Kafka keeps at least the last value for each key. Older values for the same key are removed in the background by the log cleaner. Offsets never change. 3 This suits a topic of "current state per key", such as customer addresses.

To delete a key, you send a tombstone: a message with that key and a null value. 3 Kafka keeps the tombstone for delete.retention.ms, one day by default. 5 A consumer that falls further behind than that can miss the delete. 3

Producers: partitioner, batching and acks

A producer sends each message straight to the leader of its partition. 3 If the message has a key, the default partitioner hashes the key to pick the partition. With no key, it sticks to one partition until at least batch.size bytes have gone there, then moves on. 6

The producer groups messages for the same partition into batches. batch.size caps a batch at 16,384 bytes by default. linger.ms lets the producer wait a little for more messages. Kafka 4.0 changed its default from 0 to 5 ms. 6 Bigger batches mean fewer requests and more throughput, for a few milliseconds of extra delay.

The acks setting decides when the producer hears "ok". 6

  • acks=0: the producer does not wait at all. Retries do nothing.
  • acks=1: the leader writes to its own log and answers. If it dies before followers copy the message, the message is lost.
  • acks=all: the leader waits for every in-sync replica. This is the default.

The idempotent producer needs acks=all, and stops retries from writing duplicates.

Replication: the ISR and the high watermark

Each partition has one leader and zero or more followers. Followers fetch from the leader, much like a consumer. 3 A follower stays in the ISR while it keeps its session with the controller and keeps up. If it lags longer than replica.lag.time.max.ms, the leader removes it. 3

A message is committed when all in-sync replicas have it. Consumers see only committed messages. 3 The high watermark marks the end of that committed part of the log. 7 Kafka promises that a committed message is not lost "as long as there is at least one in sync replica alive". 3

Now the trap from Jepsen. "All in-sync replicas" can mean just the leader. acks=all then means one copy. The fix is min.insync.replicas. With acks=all, a write fails with NotEnoughReplicas when the ISR is smaller than this number. 5 Its default is 1. The docs suggest 3 replicas with min.insync.replicas=2. 5

Step through a partition losing replicas. Use Next and Back, or the ← and → keys.

How the ISR, acks=all and min.insync.replicas decide what is safe1 partition · 3 replicas · min.insync.replicas=2 B1 leader B2 B3 0–5 (5 new)0–40–4ISR = B1, B2, B3Consumers can read up to 4 0–50–50–5✓ all ISR have 5: ack, readable 0–60–60–5B3 is too far behind: out of the ISRISR = B1, B2. 2 ≥ 2, so 6 is acked 0–60–5ISR = B1 only. 1 < 2Write 7 fails: NotEnoughReplicas 0–5B3 lacks 6. Unclean election is off,so the partition waits for B1 SeniorPath
  1. A producer with acks=all sends offset 5. The leader, B1, appends it. B2 and B3 have not fetched it yet, so consumers can still read only up to offset 4.
  2. B2 and B3 fetch offset 5. Now every in-sync replica has it. The leader acks the producer, and the high watermark moves, so consumers can read offset 5.
  3. B3 falls too far behind and leaves the ISR. Two replicas are still in sync, which meets min.insync.replicas=2. Offset 6 is acked with two copies.
  4. B2 crashes. Only the leader is in sync. With acks=all, the write fails with NotEnoughReplicas. The producer sees an error, not a false ack.
  5. B1 crashes too. Only B3 is left, and it is missing offset 6. With unclean election off (the default), Kafka keeps the partition offline until B1 returns (or, with eligible leader replicas on, an ELR member can lead). It does not lose offset 6.
Step 1 of 5

If every in-sync replica dies, Kafka must choose. It can wait for one to come back, or elect any replica that returns first, even one that is behind. The second choice keeps the partition up but may lose committed messages. 3 That is unclean leader election. unclean.leader.election.enable is false by default. 5 Even then, a lone last replica that crashes uncleanly can lose committed data. 7 KIP-966 adds Eligible Leader Replicas to close this gap. They are on by default in new clusters since Kafka 4.1, but not in 4.0. 8

Consumer groups, offsets and rebalances

Each consumer group has a group coordinator on one broker. When a consumer commits offsets, the coordinator writes them to __consumer_offsets, a compacted topic that keeps the latest commit per partition. 10 By default, the consumer commits offsets every 5 seconds in the background. 9

When a member joins, leaves or stops answering, the group rebalances: partitions move between members. A member that is silent for session.timeout.ms (45 seconds by default) is removed in the classic protocol. With KIP-848, the broker sets this timeout. A member is also removed if it does not call poll() within max.poll.interval.ms (5 minutes). 9

In the old "eager" protocol, every member gives up all its partitions, then waits for a new assignment. Nobody reads during that pause. 11 Cooperative rebalancing, from Kafka 2.4, revokes only the partitions that change owner. Everyone else keeps reading. 11 For the classic protocol, choose CooperativeStickyAssignor. 9

The newer protocol from KIP-848 is generally available since Kafka 4.0. It is "fully incremental" and the broker computes the assignment. 12 On the client it is still off by default: set group.protocol=consumer. The docs expect it to become the client default in Kafka 5.0. 12

Consumer lag is how far a group is behind the end of each partition. kafka-consumer-groups.sh --describe shows the current offset, the log end offset and the lag for each partition. 13 Watch it. Lag that keeps growing is your backpressure signal.

Ordering, and the partition count

Kafka keeps order only inside a partition. Same key, same partition, same order. Across partitions there is no order.

That is why the partition count is hard to change for keyed data. Roughly, the default partitioner picks hash(key) % number_of_partitions. When you add partitions, messages for a key "may be routed to different partitions". Kafka does not move the old data. 13 For a while, one key's events sit in two partitions, and a consumer can read them out of order. Kafka also cannot reduce the number of partitions. 13 So pick the count for your peak load, with room to grow.

KRaft controllers

Kafka now keeps cluster metadata in its own log, run by controllers. This is KRaft mode, covered in ZooKeeper, etcd and coordination. A server can be a broker, a controller, or both. Most clusters run 3 or 5 controllers. A majority must stay alive, so 3 survive one failure and 5 survive two. 14 Don't run combined mode in critical production. 14

Section 4 of 8

Trade-offs

OptionLose acked writes?CostUse it when
acks=0Yes You never know if it arrived.Fastest.Metrics where a gap is fine.
acks=1Yes , if the leader dies before followers copy it.One round trip to the leader.Logs you can lose a little of.
acks=all, min.insync.replicas=1Yes , when the ISR shrinks to the leader.Waits for the ISR.Rarely. This is the default pair, so check it.
acks=all, 3 replicas, min.insync.replicas=2No , while one in-sync copy survives.Writes fail when 2 of 3 brokers are down.Orders, payments, anything you must keep.
Unclean leader election onYes The partition comes back sooner.Almost never.
Cooperative or KIP-848 rebalancingn/aNeeds a client upgrade or config change.Large groups, frequent deploys.

Simple rule: for data you must not lose, use 3 replicas, acks=all and min.insync.replicas=2. Leave unclean election off.

Section 5 of 8

At work: how a senior uses this

  • Read the topic config before you trust a topic. Ask: "What is min.insync.replicas, and what happens if two brokers die?"
  • Pick the key and the partition count on day one. Write both in the topic's README, with where order holds.
  • Alert on consumer lag per partition, not just per group. One hot partition can hide in an average.
  • Find out why a group rebalances. Slow handlers that miss max.poll.interval.ms cause rebalances that cause more lag.
  • Move consumers to cooperative or KIP-848 rebalancing before scaling a group up.
  • For compacted topics, set delete.retention.ms longer than your slowest consumer can fall behind.
Section 6 of 8

With AI

What to ask the agent

"List every Kafka topic in this repo's config with its replication factor, min.insync.replicas, cleanup.policy and retention.ms. Flag any topic where acks=all gives only one copy."

"Our consumer group rebalances every few minutes. Read this consumer code and config, and find what could make a member miss max.poll.interval.ms."

"We want to grow this keyed topic from 12 to 24 partitions. Write a plan that keeps per-key order, for example a new topic and a cut-over."

What to check yourself

  • The agent did not claim acks=all alone means "on 3 brokers". It means "on every replica in the ISR right now".
  • Any partition change for a keyed topic has a plan for old and new messages of the same key.
  • Offsets are committed after the work, not by a timer in the middle of it.
  • Config changes name the Kafka version. Defaults like linger.ms changed in 4.0.
  • Nobody turned on unclean leader election to "fix" an offline partition without saying what data it loses.
Section 7 of 8

Check yourself

1. A topic has 3 replicas and min.insync.replicas=2. Two brokers are down. A producer with acks=all sends a write. What happens?

Show answer

The write fails with NotEnoughReplicas, so the producer knows it was not stored safely. With acks=all, a write needs at least min.insync.replicas in-sync copies. One is not enough, so Kafka returns an error instead of a weak ack.

2. Events for one order must be read in the order they were sent. What do you do?

Show answer

Use the order ID as the key, so all its events go to one partition. Kafka keeps order only inside a partition. The key hash sends every event of one order to the same partition.

3. You grow a keyed topic from 6 to 12 partitions. What changes?

Show answer

New messages for a key may go to a different partition than its old messages, so order per key can break. Kafka does not move existing data. The key-to-partition mapping changes with the count, and Kafka cannot reduce partitions either.

4. What does a tombstone do on a compacted topic?

Show answer

It marks a key as deleted. After compaction and a delay, the key's older values and then the tombstone itself go away. A tombstone is a message with a key and a null value. Compaction keeps the latest value per key, so the delete wins, and the marker is removed after delete.retention.ms.

Your progress is saved only in this browser. Export it to keep it safe.

Was this clear?
Report a mistake (opens GitHub in a new tab)
Section 8 of 8

Go deeper

Show 14 sources and related lessons
  1. Kyle Kingsbury, “Jepsen: Kafka” (September 2013) (opens in a new tab)
    A test of Kafka 0.8's replication before its release. A leader alone in the ISR acks writes, then a lagging follower is elected and 520 acked writes are lost.
  2. KIP-106 - Change Default unclean.leader.election.enabled from True to False (opens in a new tab)
    The proposal to protect data by default instead of electing a replica that is behind.
  3. Apache Kafka documentation: Design (Kafka 4.3) (opens in a new tab)
    The Replication section (ISR, committed messages, unclean leader election, durability settings) and the Log Compaction section.
  4. Apache Kafka documentation: Log (Kafka 4.3) (opens in a new tab)
    How a partition is stored as segment files named by offset, how reads find an offset, and why deletion works one segment at a time.
  5. Apache Kafka documentation: Topic Configs (Kafka 4.3) (opens in a new tab)
    segment.bytes, retention.ms, cleanup.policy, min.insync.replicas and unclean.leader.election.enable, with their defaults.
  6. Apache Kafka documentation: Producer Configs (Kafka 4.3) (opens in a new tab)
    acks, linger.ms, batch.size and how the default partitioner picks a partition.
  7. KIP-966: Eligible Leader Replicas (opens in a new tab)
    Defines the high watermark (one line on consumer visibility is inverted; see the design doc) and describes how the last replica in the ISR can still lose committed data.
  8. Apache Kafka documentation: Eligible Leader Replicas (Kafka 4.3) (opens in a new tab)
    Which replicas outside the ISR may safely become leader, the election order, and when the feature is on by default.
  9. Apache Kafka documentation: Consumer Configs (Kafka 4.3) (opens in a new tab)
    group.protocol, partition.assignment.strategy, session.timeout.ms, max.poll.interval.ms and auto-commit.
  10. Apache Kafka documentation: Distribution (Kafka 4.3) (opens in a new tab)
    The group coordinator and the compacted __consumer_offsets topic.
  11. KIP-429: Kafka Consumer Incremental Rebalance Protocol (opens in a new tab)
    Why the old protocol makes every member give up all its partitions, and how cooperative rebalancing moves only the ones that change owner.
  12. Apache Kafka documentation: Consumer Rebalance Protocol (Kafka 4.3) (opens in a new tab)
    The KIP-848 protocol, how to turn it on, and the plan to make it the default.
  13. Apache Kafka documentation: Basic Kafka Operations (Kafka 4.3) (opens in a new tab)
    What adding partitions does to keyed data, and how to check consumer lag with kafka-consumer-groups.sh.
  14. Apache Kafka documentation: KRaft (Kafka 4.3) (opens in a new tab)
    Controller and broker roles, how many controllers to run, and the metadata log.

Case studies: LinkedIn: How Kafka reached 2 million writes a second on cheap machines · PhonePe: Moving 100 billion events a day into Kafka

Related: Queues vs logs and delivery guarantees · Replication · Exactly-once and effectively-once · Backpressure and flow control · Schema evolution and encoding · Coordination services: ZooKeeper and etcd · Stream processing · Sharding and consistent hashing

Before this: Queues vs logs and database replication. Related: exactly-once and effectively-once for the idempotent producer and transactions, schema evolution and encoding for message formats, stream processing, and sharding and consistent hashing for why changing a partition count moves keys.

Term

See full entry

Jump to a section

  1. 1What broke
  2. 2The idea in simple words
  3. 3How it works
  4. 4Trade-offs
  5. 5At work
  6. 6With AI
  7. 7Check yourself
  8. 8Go deeper