Vivek's Field Notes

Apache Kafka

β€’ 26 min read

Kafka is often called a “message queue”, but at its heart it is something simpler: a log. Once you understand the log, almost every Kafka design decision follows from it.

1. What is a log?

A log is a data structure with two rules:

  1. Append only. You only ever add records at the end. Nothing is updated in place.
  2. Ordered. Records stay in the order they were appended. Each one gets a number, its offset.
01234567offsetold records on the left Β· new records always land at the end β†’
Writers only append. Readers move left to right. Nobody edits the middle.

Logs inside databases

Databases already depend on logs:

Logs in distributed systems

When you have a leader and replicas, the hard question is: how do they stay consistent? There are two classic answers, and both are built on an ordered log.

ModelHow it worksWhy the log matters
Active-active (state machine replication)Leader and replicas all apply the same instructionsEveryone must apply them in the same order, and the log gives that order
Primary-backupThe primary does the work, then copies the result to the backupsThe log is the stream of results being copied

Kafka takes this idea and turns it into a product: a log that many machines can write to and read from.

2. Why Kafka is fast on “slow” disks

Disks are slow only at random access

Kafka stores everything on disk, and people say disks are slow. That is only true for random access, when the disk head has to jump around. Kafka’s log is append only, so:

Kafka also doesn’t keep its own cache. It writes to the OS page cache and lets the operating system flush to disk in the background. Data sitting in the page cache can be lost if the machine dies before the flush, and that is why Kafka relies on replicas on other machines for durability.

Why not just use a database?

A traditional design puts messages in a database table, backed by a B-tree.

B-tree (database)Log (Kafka)
Lookup costO(log n), which sounds fast…O(1) to append, sequential to read
On a real diskEach level can be a random seek, which is slowPure sequential I/O
MaintenanceRebalancing the tree on writes is costlyNothing to rebalance
Readers vs writersCompete for locks and pagesWriters at the end, readers behind: they don’t block each other
Keeping old dataExpensiveDisks are cheap, so keep messages for days or weeks

Zero-copy: skip user space

To send data to a consumer, a normal program reads the file into its own memory (user space) and then writes it back to a socket. The bytes cross the kernel/user boundary twice, and the CPU does the copying.

Kafka uses the sendfile system call instead. The bytes go straight from the page cache to the network card, all inside the kernel, mostly by DMA. The CPU stays free.

Normal read() + write()4 copies, 2 of them by the CPUDiskPage cacheApp bufferuser spaceSocket bufferNICKafka: sendfile()never leaves the kernelDiskPage cacheuser space skippedNIC
Same bytes, same destination. The blue path is shorter and doesn't burn CPU on copies.

Compress the batch, not the message

Compressing each message on its own is wasteful: small messages compress badly. Kafka compresses a whole batch instead:

  1. The producer compresses the batch once.
  2. The broker stores it as is, still compressed.
  3. The consumer decompresses it.

One compression, one decompression, and the broker never pays for either.

3. Producers

Vocabulary

TermMeaning
BrokerOne Kafka server
TopicA named stream of messages, e.g. page_views
PartitionA topic split into several separate logs
LeaderThe one broker in charge of a partition. All writes go to it; other brokers hold copies (replicas)

The user picks how many partitions a topic has. Each partition has its own leader, and the leaders are spread across brokers. A topic pg with 3 partitions might look like this: b0 leads P2, b1 leads P1, b2 leads P0.

Batching: when does the producer send?

The producer doesn’t send each message right away. It fills a batch and sends when either the batch is full or a wait time runs out (batch.size and linger.ms).

Big batchesSmall batches
ThroughputHighLow
CompressionBetterWorse
LatencyHigherLower

No load balancer in the middle

If producers sent to a load balancer, which then forwarded to the right broker, every message would take two network hops. Kafka avoids that:

  1. The producer asks any broker: “who leads each partition of this topic?” Every broker knows the answer.
  2. It then sends batches directly to the leader of the right partition.

Which partition?

The keyed option is the important one. All messages for a user (key = user_id) land in the same partition, so:

Producerhash(key) % 3P0 Β· leader b2key = user BP1 Β· leader b1key = user AP2 Β· leader b0key = user C
Each color is one key. The same key always takes the same path, so its messages stay in order.

4. Consumers

A consumer asks the partition leader: “give me data starting at offset X”. The broker sends messages from X onward.

Push vs pull

PushPull
Who decides the speed?The senderThe receiver
Kafka uses it forProducer β†’ brokerBroker β†’ consumer

Why pull for consumers? With push, a fast producer can flood a slow consumer and crush it. With pull, each consumer asks for “data from offset X, up to Y MB” and takes only what it can handle.

Long polling

Pull has one problem. If there is no new data, the consumer keeps asking and gets nothing back: a busy wait that wastes CPU and network.

Kafka fixes this with long polling. The consumer says: “if you have nothing, hold my request for up to T ms, and reply as soon as at least N KB arrives” (fetch.max.wait.ms, fetch.min.bytes).

One consumer per partition

Within a consumer group, each partition is read by exactly one consumer at a time. One consumer can read several partitions, but two consumers never share one.

Why? If two consumers read the same partition, a slow acknowledgement could let both process the same message, and the order would be lost. With one reader per partition, the progress is just one number, the offset, instead of per-message acks.

Static membership: give each consumer a group.instance.id. If it restarts, it gets the same partitions back without a full rebalance of the group.

5. How many partitions?

More partitions means more throughput. For a target throughput t, with p = what one producer can push into one partition and c = what one consumer can read from one partition:

1partitions = max(t / p, t / c)

Example: t = 100 MB/s, p = 20 MB/s, c = 10 MB/s β†’ max(5, 10) = 10 partitions.

Don’t overdo it. Every partition is a set of open files on the broker, and more partitions means slower leader elections and rebalances.

6. Offsets: four positions in one partition

012345678910last committedcurrent positionhigh watermarklog endorange: read but not committed (replayed after a crash)leader only
PositionMeaningReading a book
Last committed (1)Last progress saved to KafkaThe bookmark you put in
Current position (6)Where the consumer is actually readingThe page your eyes are on
High watermark (9)Last message copied to all in-sync replicasPages printed in every copy of the book
Log end (10)Last message written to the leaderPages the author has written so far

Two rules follow:

  1. After a crash, the next consumer resumes from the committed offset, not the current position. Here the consumer read up to 6 but only saved 1. Whoever takes over starts at 1, so messages 1–5 are processed again.
  2. Consumers can only read up to the high watermark. Messages past it exist only on the leader. If the leader dies they could disappear, so Kafka hides them until they are replicated. You never read something that could later vanish.

7. Committing offsets

Delivery guarantees

The order of “process” and “commit” decides what happens on a crash:

StrategyOrderOn crashResult
At least onceProcess, then commitMessages after the last commit are processed againNo loss, possible duplicates
At most onceCommit, then processCommitted but unprocessed messages are skippedNo duplicates, possible loss

At least once is the common choice. Make your processing idempotent so duplicates don’t hurt.

How often to commit

WhenVerdict
After every message❌ A round trip per message clogs the network and kills throughput
After every N messagesβœ…
After each batch from a partitionβœ…
Auto-commit every X secondsβœ… Simple, but you may replay up to X seconds of work

commitSync vs commitAsync

commitSynccommitAsync
Waits for the broker?Yes, blocksNo, keeps processing
Retries on failure?YesNo (a late retry could overwrite a newer commit)
ThroughputLowerHigher
Learn about failureImmediatelyLater, in a callback

A common pattern: commitAsync in the normal loop for speed, and one commitSync on shutdown or rebalance so the final position is saved for sure.

8. Consumer lag

1lag = log end offset βˆ’ committed offset

Lag is how far behind the consumer is.

Lag is the first number to watch on any Kafka dashboard.

9. Producer reliability: acks, retries, idempotence

Four producer settings decide whether a message can be lost, duplicated or reordered.

acks: when does the leader say “OK”?

acks“OK” meansSpeedIf the leader dies just after
0Nothing. The producer doesn’t wait at allFastestThe message may never have arrived, and you won’t know
1The leader wrote it to its own logFastLost, because the followers hadn’t copied it yet
all (same as -1)Every in-sync replica has itSlowerSafe, as long as one in-sync replica survives (but see the trap)

Default: all since Kafka 3.0. Whatever the producer picks, consumers only see a message once it is committed.

retries: resend on failure?

Failures like “leader is changing” or “network timeout” are transient, so resending usually works.

Retries cause two problems.

Problem A: duplicates. The broker wrote the batch, but the producer never heard back, so it sent it again.

1Producer sends batch B   ──► Leader writes B βœ“
2Producer ◄── "OK" lost on the network βœ—
3Producer times out, retries ──► Leader writes B AGAIN ❌ duplicate

Problem B: reordering. This only happens with more than one request in flight.

1Send batch 1  ──► fails βœ—
2Send batch 2  ──► succeeds βœ“  (offset 100)
3Retry batch 1 ──► succeeds βœ“  (offset 101)
4Log order: 2, 1 ❌   You sent 1, 2.

max.in.flight.requests.per.connection

“In flight” means sent but not yet acknowledged.

ValueBehaviourTrade-off
1Send, wait for “OK”, send the nextOrder is safe, but you wait a full round trip every time
5 (default)Send up to 5 before waitingMuch faster because the pipe stays full, but Problem B can happen

Think of letters. With 1 in flight you post a letter and wait for the reply before posting the next. With 5 you post five, and if letter 1 gets lost and is re-posted, it arrives after letter 2.

The old trade-off was fast (5) or ordered (1): pick one. Idempotence removes it.

enable.idempotence: the fix for both problems

Idempotent means doing something twice has the same effect as doing it once. Here is how it works:

  1. The broker gives the producer a Producer ID (PID).
  2. The producer tags every batch with a sequence number per partition: 0, 1, 2, 3…
  3. The broker remembers the last sequence number it accepted for each PID and partition.
Broker receivesBroker does
Sequence = last + 1βœ… Writes it
Sequence ≀ last (already seen)Drops it as a duplicate, but still replies “OK”. This fixes Problem A
Sequence > last + 1 (a gap)Rejects it as “out of order”, and the producer resends in the right order. This fixes Problem B
ProducerPID 42Brokerremembers last seqβ‘  send batch, seq 3β‘‘ "OK" on its way backβ‘’ retry, seq 3written, last seq = 3 βœ“βœ— lost on the network3 ≀ 3 β†’ duplicate dropped, still replies OK
The retry carries the same sequence number, so the broker can tell it is a duplicate.

Default: true. Idempotence requires all three of these:

Why ≀ 5? From the docs: “the broker only retains at most 5 batches for each producer.” The broker keeps the last 5 batches per producer for duplicate checking. With more than 5 in flight, it may already have forgotten an older batch and can’t tell whether a retry is a duplicate.

10. Replication

Every partition is copied to several brokers, for example 3 copies.

Leader Β· b1producers write hereFollower Β· b2in ISRFollower Β· b3laggingβœ— stuck too long β†’ removed from ISRISR = the replicas that are caught up enough to count
b2 keeps up and stays in sync. b3 falls behind and gets dropped, so writes stop waiting for it.

ISR: in-sync replicas

The leader keeps a list of followers that are “caught up enough”, the ISR. It matters for two reasons:

  1. A message is committed (safe) only when every member of the ISR has it. Only then does an acks=all producer get “OK, saved”.
  2. If the leader dies, the new leader is picked only from the ISR. Every ISR member has every committed message, so nothing is lost.

That creates a tension:

Who stays in the ISR?

Today a replica must pass two checks:

ConditionChecked byFails when
Heartbeating the controller (the cluster’s manager)ControllerNo heartbeat within broker.session.timeout.ms, so the broker counts as offline
Keeping up with the leaderLeaderNot caught up for replica.lag.time.max.ms

The old rule, and why it was dropped

Kafka 0.8.2 used two settings:

  1. replica.lag.time.max.ms: “if a follower hasn’t asked me for data in X ms, it’s stuck. Kick it out.” This worked fine, and it is still the rule today.
  2. replica.lag.max.messages: “if a follower is more than N messages behind, it’s slow. Kick it out.” This was the problem.

Why is “number of messages behind” a bad rule? To set N correctly you’d have to guess your traffic: how big your batches will be, on every topic, forever. One cluster has many topics with different traffic, and traffic changes over time. A single burst can put a perfectly healthy follower N messages behind for a moment, and it gets kicked out. No single number works for all topics, so the count-based setting was removed and only the time-based rule remains.

The core guarantee

A committed message is never lost as long as at least one in-sync replica stays alive.

Why not majority voting?

Approach A: majority voting (Raft, Zab, Paxos)

The upside is that latency depends on the fastest majority. With 3 copies you wait for the faster follower and can ignore the slow one. The downside is cost: surviving 1 failure needs 3 copies, and surviving 2 needs 5. That is 5Γ— the disk and roughly β…• the throughput.

Approach B: Kafka’s ISR

To survive 1 failureMajority voteKafka ISR
Copies needed32
Acks waited for1 follower1 follower
Disk cost3Γ—2Γ—
Slow followerIgnored, only the faster majority countsSlows commits until it’s removed from the ISR

Kafka’s reasoning: for large volumes of data, storing 3 to 5 copies of everything costs too much. That’s why majority voting is usually kept for small metadata (ZooKeeper, KRaft, the HDFS NameNode journal) while bulk data uses cheaper schemes. The slow-follower downside is limited because slow replicas get removed from the ISR.

The closest academic design to Kafka is PacificA (Microsoft Research). You don’t need to know it in detail, but mentioning it in an interview is a bonus.

Bonus: no fsync needed

Many consensus algorithms assume a crashed node comes back with all its data intact, which means calling fsync on every write. That can be 100–1000Γ— slower. Kafka doesn’t assume this. A replica that crashes must fully catch up again before it rejoins the ISR, even if it lost data that was never flushed to disk. Safety comes from copies on other servers, not from forcing every write to disk. This is the replica-based durability from section 2.

Unclean leader election: what if every ISR replica dies?

The guarantee needs at least one in-sync replica alive. When none are left, there are two choices:

OptionResultPicks
Wait for an ISR replica to come backPartition is down until it returns, and down forever if its disk is goneConsistency (no data loss)
Take any replica that comes back, even one not in the ISRPartition is back up fast, but messages it never received are lostAvailability

The acks=all trap β†’ min.insync.replicas

acks=all means every replica currently in the ISR, not every replica that exists.

1RF = 2. One broker dies        β†’ ISR = {leader}
2acks=all now means "the leader alone has it" β†’ write succeeds
3Leader dies                    β†’ message lost πŸ’€

Two settings fix this:

  1. unclean.leader.election.enable=false: never promote a replica that isn’t in sync.
  2. min.insync.replicas=2: an acks=all write succeeds only if the ISR still has at least 2 members. If it shrinks below that, the producer gets a NotEnoughReplicas error instead of a false “OK”.

The common production setup is RF = 3, min.insync.replicas=2, acks=all. You can lose one broker and keep accepting writes, and every acknowledged write is on at least two machines.

11. Exactly once: transactions

Idempotence stops duplicates from a single producer’s retries. Real apps do more: they read from one topic and write to another. Take a payment processor that reads payments from payments and writes debits to ledger. Three things can go wrong:

#FailureWhat goes wrongFix
1Producer retries a send after a lost ackThe debit is written twiceIdempotent producer (section 9)
2App crashes after writing the debit but before saving its offsetOn restart it reads the payment again and writes the debit againAtomic transactions
3An app is wrongly declared dead and a replacement starts, but the old one is still running (a “zombie”)Two instances write the same debitsZombie fencing

Failure 2, step by step:

1read payment βœ“  β†’  write debit βœ“  β†’  πŸ’₯ crash  β†’  save offset βœ—

On restart the committed offset still points at the payment, so the app reads it again and writes the debit again.

Failure 3: instance #1 freezes, say on a long GC pause or a network blip. The system decides it’s dead and starts instance #2. Then #1 wakes up and keeps working. Now two instances are writing the same debits.

Transactions fix failures 2 and 3.

The key trick: “consumed” is just another write

Kafka records that a message was consumed by writing its offset to an internal topic, __consumer_offsets. Committing an offset is therefore a write to a partition, just like writing the debit.

So the problem becomes: two writes have to happen together, the debit and the offset. A transaction gives you exactly that. All writes in it become visible together, or none do.

1begin transaction
2   write debit    β†’ ledger
3   write offset   β†’ __consumer_offsets
4commit transaction β†’ both become real at once
paymentsinput Β· tp0Appread β†’ processledger Β· tp1the debit__consumer_offsets"payment consumed"one transactionCOMMIT: both visible βœ“
Until the commit, consumers reading with isolation.level=read_committed see neither write.

If the app crashes before the commit, both writes are thrown away. On restart it reads the payment again, and that is fine, because the first debit never became visible. Exactly one debit ends up in the ledger.

Zombie fencing

Instance #1 (zombie)epoch 5Instance #2epoch 6Brokerpayment-processor-0 β†’ epoch 6epoch 6 = current β†’ written βœ“epoch 5 < 6 β†’ rejected βœ—
Like a hotel that changes the key-card code for each new guest: the previous guest's card stops working.

It’s the same idea as a fencing token, or a term number in Raft. If you know one of them, you know this.

The catch: fencing only works if the same input partitions always map to the same transactional.id. If payments partition 0 was handled by T0 and later moves to T1, Kafka sees two different ids and nothing stops T0 from writing alongside T1. The mapping has to stay fixed, e.g. id = “processor for partition 0”. Kafka Streams does this for you by deriving the id from the input partition.

How it works inside

1Producer ──(1) initTransactions / addPartitions / commit ──► Transaction Coordinator
2                                                               β”‚ (runs inside a broker)
3                                                               β–Ό
4                                                      __transaction_state topic
5                                                      (stores txn state only, not data)
6Producer ──(2) normal sends ──► tp1, tp2, __consumer_offsets
7Coordinator ──(3) COMMIT / ABORT markers ──► every partition in the txn
  1. The producer registers with the transaction coordinator and tells it which partitions the transaction touches. The coordinator logs this in __transaction_state.
  2. The actual messages go straight to their partitions as usual, offsets included.
  3. On commit, the coordinator writes a COMMIT marker into every partition involved. read_committed consumers only deliver messages once they see that marker, and skip aborted ones.

12. Backpressure: when the consumer is slower than the producer

Producers write 1,000 msg/s, the consumer handles 500 msg/s. A backlog builds up. The good news: the backlog waits safely in Kafka, not in your app. The job is to slow down without getting kicked out of the group.

Symptoms

SymptomWhat’s happening
Lag increasingThe consumer’s position falls further behind the newest message
Memory pressureYou fetched too many records at once and they’re sitting in RAM
RebalancingProcessing one batch took longer than max.poll.interval.ms, so you’re kicked, and the next owner re-reads, causing duplicates
Timeout errorsHeartbeats stopped (the process is frozen or dead) for longer than session.timeout.ms

Pause and resume, step by step

 1while (true) {
 2    checkAndResumePartitions();                          // 1
 3    records = consumer.poll(Duration.ofMillis(1000));    // 2
 4    for (TopicPartition partition : records.partitions()) {
 5        int recordCount = records.records(partition).size();
 6        partitionBacklog.put(partition, currentBacklog + recordCount);   // 3
 7        if (partitionBacklog.get(partition) > backlogThreshold) {
 8            pausePartition(partition);                   // 4
 9        }
10        for (ConsumerRecord record : records.records(partition)) {
11            try { processRecord(record); }
12            finally { backlog -= 1; }                    // 5
13        }
14    }
15}
  1. For each paused partition, if its counter is under 500 (half of 1,000), resume it.
  2. Ask Kafka for records and wait up to 1 s. Paused partitions return nothing, but this call still tells Kafka “I’m alive”. That’s the point of pausing instead of stopping.
  3. For each partition that returned records, add the count to its counter. Got 100 from partition 0, so counter[P0] += 100.
  4. If the counter is over 1,000, pause this partition.
  5. Each finished record lowers the counter again.

Pausing at 1,000 and resuming at 500 (not at 999) stops the partition from flipping on and off every poll. That gap is called hysteresis.

The other tools

What to watch: consumer lag. The real danger is lag growing older than the topic’s retention: Kafka then deletes messages nobody has read yet.

Long jobs: pause the container (Spring Kafka example)

Settings: max.poll.records = 1 (one message per poll), max.poll.interval.ms = 30s, concurrency = 20 (20 consumer threads).

When a message arrives:

  1. Pause the container: “give me nothing more”.
  2. Hand the message to a background thread (executor), which starts the long job.
  3. The listener function returns immediately, so the main thread goes back to polling. It gets nothing, but stays alive.
  4. When the job finishes (success or error), resume the container: “OK, give me the next one”.

So each consumer handles one message at a time, in the background, and keeps polling in the foreground so the group knows it’s alive. A job can take 10 minutes even though the deadline is 30 s, because polling never stops.

The weak spot (the offset trap from earlier): Spring commits the offset when the listener function returns, which is step 3. The job is still running at that point. If the app crashes at minute 5 of the job:

The fix: turn off auto-commit and commit manually inside the success callback (step 4), after the job really finished.

13. Schema evolution

Kafka keeps messages for days and lets you replay them. So one topic always holds data written by several versions of the producer code, read by several versions of the consumer code. You can’t upgrade everything at once. The schema has to change in a way both sides survive.

Two directions

NameMeansNeeded when
Backward compatibleNew code reads old dataYou upgrade consumers first (and always, for replay)
Forward compatibleOld code reads new dataYou upgrade producers first
FullBothEither side can deploy first

Protobuf: fields are numbers

On the wire, each field is tag number + type + value. Field names are never sent.

Avro: no tags, two schemas

Avro binary is just the values back to back, in schema order. No tags, no names. You cannot decode it without the exact schema it was written with (the writer’s schema). The reader also has its own schema (the reader’s schema), and Avro matches fields between the two by name:

The rule for both formats: add optional fields, never rename or retype, never reuse a field id.

Schema Registry: how the consumer finds the writer’s schema

Avro needs the writer’s schema, but sending the whole schema with each message would be wasteful. The Schema Registry solves that:

1Producer ──register schema──► Schema Registry ──► schema ID 42
2Producer ──► Kafka message = [magic byte 0][4-byte schema ID = 42][payload]
3Consumer ──reads ID 42──► Registry (cached) ──► writer's schema ──► decode

At registration, the registry checks compatibility against the previous versions and rejects a breaking schema before any bad message is produced. Modes: BACKWARD (default), FORWARD, FULL, NONE, plus _TRANSITIVE variants that check against all past versions, not just the last one. BACKWARD means “upgrade consumers first.”

In my project: Narad

Narad sends plain JSON events, with no registry. How it copes (internal/consumer/kafka.go):

ChangeWhat happens
Producer adds a new fieldGo’s encoding/json ignores itForward βœ… (field not stored)
Old event has no idID built from topic/partition/offset, so replay is idempotentBackward βœ…
No ts / service / levelKafka time / "unknown" / "INFO"Backward βœ…
New business IDGoes into the dims map, no schema changeβœ…
Rename msg β†’ messageDecodes fine, msg stored empty, no alert❌ silent
ts sent as a numberDecode fails β†’ dead-letter topic❌ loud, but caught

The gap: a rename passes silently. The fix is Protobuf or Avro with a Schema Registry in BACKWARD mode, so the bad schema is rejected when it’s registered, before any message is sent.

#Blog #Kafka #Distributed-Systems #Backend #System-Design #Notes