Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Handbooks  /  The Kafka Handbook
Handbook~14 min readIntermediate
Deep Dive

Kafka, and the
log that isn't a queue.

Kafka gets called a "message queue," and that framing hides everything interesting about it. It's a distributed, append-only log: events are written once and read many times, retained, replayable, and consumed by many teams at once. Once you see the log, the rest falls into place.

01

A log, not a queue

A traditional message queue delivers a message to one consumer and then deletes it — the message is consumed and gone. Kafka is different: it's a distributed append-only log. Producers append records to the end; the records are retained (for days, or forever); and each consumer reads forward at its own pace, tracking where it is rather than removing anything.

That one design choice unlocks Kafka's superpowers: records can be re-read (replay history, reprocess after a bug, bootstrap a new system), and many independent consumers can each read the whole stream — analytics, a search indexer, and a fraud detector all consuming the same events without interfering. The queue mindset ("deliver and delete") misses all of it.

→ The mental flip

Don't think "messages I send and someone removes." Think "an ordered log of facts that happened, kept around, that anyone can read from any point." Kafka is a source of truth for event streams, not a mailbox.

02

Topics, partitions & offsets

Records go into topics (named streams, like orders or clicks). For scale, a topic is split into partitions — each an independent, ordered, append-only sequence. Every record in a partition gets a monotonically increasing offset: its position in that partition's log. A consumer's progress is just "I'm at offset 4,201 in partition 2."

Topic "orders" — 2 partitions, each an ordered log
Partition 0
01234 ← end
Partition 1
012 ← end
Producers append to the end; consumers read forward, remembering their offset per partition.

Partitions are the heart of Kafka: they're the unit of parallelism, of ordering, and of distribution (partitions of a topic spread across the cluster's brokers). Almost every Kafka behavior traces back to "it's per-partition."

03

Producers, consumers & groups

Producers append records to a topic (choosing a partition, usually by key — next section). Consumers read them. The clever part is the consumer group: a set of consumers that cooperatively read a topic, where Kafka assigns each partition to exactly one consumer in the group. Add consumers to a group and Kafka rebalances partitions across them — that's how you scale processing horizontally.

The catch: partitions cap your parallelism. A group can have at most as many active consumers as the topic has partitions; extra consumers sit idle. Meanwhile, different consumer groups are fully independent — each reads the entire stream with its own offsets — which is exactly what lets many applications consume the same topic without stepping on each other.

→ Sizing rule

Choose partition count for your peak parallelism: you can't have more working consumers in a group than partitions. Partitions are cheap-ish to add but you can't easily reduce them, so plan ahead.

All three moving parts are arithmetic. Parallelism is a min, the key picks the partition by hash, and lag only drains when you consume faster than you produce:

active consumers = min(P, C)  ·  partition = hash(key) mod P  ·  drain time = lag / (consume − produce)

Eight consumers on four partitions? Four work, four idle. Consume slower than you produce? Lag never drains. The runnable version below computes all three.

04

Ordering & the partition key

Here's the guarantee people most often get wrong: Kafka guarantees ordering only within a partition, never across a whole topic. Records in partition 2 are strictly ordered; records in partition 2 versus partition 0 have no defined order relative to each other, because they're processed in parallel.

So how do you keep related records in order — say, all events for one order id? You give them the same partition key. Kafka hashes the key to pick a partition, so all records with the same key land in the same partition and are therefore ordered. Same customer → same partition → in order. This is the central design decision when using Kafka: pick a key that groups the things that must stay ordered, while spreading load across partitions overall.

Keyed by order_id

  • All events for one order → one partition
  • Strict per-order ordering
  • Load spreads across orders

No key (round-robin)

  • Records scattered across partitions
  • No ordering guarantee for related events
  • Fine only if order doesn't matter
05

Replication & durability

Each partition is replicated across several brokers for durability. One replica is the leader (handles all reads and writes for that partition); the others are followers that copy the leader's log. If the leader broker dies, a follower is promoted, so the partition survives machine failure.

The key concept is the in-sync replicas (ISR) — the set of replicas fully caught up with the leader. A producer can require that a write be acknowledged by all in-sync replicas (acks=all) before it's considered committed, guaranteeing the record survives the loss of any single broker. This is Kafka's durability–latency dial: acks=all is safest but waits for replicas; acks=1 is faster but can lose the latest writes if the leader dies before followers copy them.

06

Delivery semantics

How many times might a record be processed? Kafka supports three semantics, and the honest default is the middle one.

GuaranteeMeansCost / how
At-most-onceNever processed twice; may be lostCommit offset before processing — fast, lossy
At-least-onceNever lost; may be processed twiceProcess, then commit offset — the common default
Exactly-onceProcessed once, no loss or dupIdempotent producer + transactions — more overhead

Most systems run at-least-once and make their consumers idempotent — safe to process the same record twice — because that's simpler and cheaper than true exactly-once. Kafka does offer exactly-once (via idempotent producers and transactions), but you should reach for idempotent at-least-once first and only pay for exactly-once when duplicates are genuinely unacceptable.

→ The practical stance

"Exactly-once processing" in the real world usually means "at-least-once delivery + idempotent consumers." Design your handlers so reprocessing a record is a no-op, and duplicates stop mattering.

07

Retention vs log compaction

Because Kafka keeps records, it needs a rule for how long. Time/size retention keeps records for a window (e.g. 7 days) or up to a size, then deletes the oldest — perfect for event streams where old events stop mattering. Log compaction is different: it keeps at least the latest record per key, discarding superseded older values. That turns a topic into a durable, replayable snapshot of "the current value for every key" — ideal for changelog/state topics (a user's latest profile, an account's latest balance).

Compaction is why Kafka can back stateful systems: a compacted topic is a rebuildable source of truth for current state, not just a firehose of transient events.

08

Kafka or a message queue?

Kafka isn't always the answer. Use a traditional queue (RabbitMQ, SQS) when you want simple task distribution — deliver each job to one worker, with per-message acknowledgement, priorities, and easy retry/dead-letter handling — and you don't need retention or replay. Queues are simpler for "work to be done."

Reach for Kafka when you have high-throughput event streams that multiple systems consume, when you need to replay history or reprocess, when ordering per key matters, or when the log itself is a source of truth (event sourcing, stream processing, data pipelines). The tell: many readers of the same durable, ordered stream → Kafka; distribute discrete tasks to workers → a queue.

QueueTask distribution — one job to one worker, ack/retry/priority, no replay needed.
KafkaEvent streams — many consumers, retention & replay, per-key ordering, high throughput.
RUN IT YOURSELF

Size partitions, keys, and consumer lag

Kafka's three trickiest questions — how many consumers actually work, where a keyed record lands, and whether your lag will ever drain — are all one-liners. This assigns partitions to a consumer group (watch extras sit idle when the group outnumbers the partitions), hashes an order key to a fixed partition so its events stay ordered, and computes when a backlog drains given produce and consume rates. Change the partition count, the group size, or the rates.

CPython · WebAssembly
By the numbers

Worked example: sizing an orders topic step by step

An orders topic peaks at 30,000 records/s. One consumer instance can process 4,000 records/s. It averages 10,000 records/s at 1 KB each, and the team wants 7 days of replay. These workload numbers are illustrative. Use the page’s three formulas to size it.

StepQuestionArithmeticAnswer
1Consumers needed at peak30,000 ÷ 4,000, rounded up8
2Partitions, so all 8 can workactive = min(P, C), so P ≥ 8at least 8
3Consumers go down for 10 minutes30,000/s × 600 slag = 18,000,000 records
4Drain with 8 consumers18,000,000 ÷ (32,000 − 30,000)9,000 s = 2.5 hours
5Drain with 16 consumers on 16 partitions18,000,000 ÷ (64,000 − 30,000)≈ 529 s, under 9 minutes
6Disk for 7 days of retention10,000/s × 1 KB × 604,800 s≈ 6 TB of log
7With replication factor 36.048 TB × 3≈ 18 TB across the brokers

Step 4 is the lesson. Eight partitions handle the steady peak with almost no headroom, so a ten-minute outage takes two and a half hours to recover. Doubling to 16 partitions does not change normal running at all, but it cuts recovery to under nine minutes. Headroom is what lets lag drain. Pick the partition count up front, because adding partitions later moves keys (see the mistakes below). Steps 6 and 7 are why retention is a budget line: replay costs disk multiplied by the replication factor.

Trade-offs

Cost and trade-offs: the knobs you actually turn

Here Time is the effect on latency or throughput. Space is the effect on disk, memory or capacity.

CaseTimeSpaceWhy
acks=all vs acks=1acks=all waits for every in-sync replica, so each write is slowerNo difference in storageacks=1 can lose the newest writes if the leader dies before followers copy them.
Replication factor 3, min.insync.replicas=2One extra follower round-trip per write3 copies of every byteWrites keep succeeding with one broker down, and no acked write lives on only one machine.
More partitionsMore parallel consumers, so lag drains faster (step 5)More files, replication streams and leader electionsYou cannot easily reduce the count, and adding partitions remaps keys.
Time retention (7 days)Replay any point inside the windowGrows with throughput × timeAnything older is deleted, read or not.
Log compactionA new reader rebuilds state by reading from offset 0Grows with the number of distinct keys, not with timeOnly the latest value per key is kept, so it is not an event history.
Exactly-once (idempotent producer + transactions)Transaction commits add latencySmall transaction stateCovers read-process-write inside Kafka. A write to your own database still needs an idempotent handler.
Larger producer batchesHigher throughput, a few ms more latency per recordMore producer memoryKafka’s speed comes from appending and sending in batches. Tiny batches throw that away.

Almost every row trades latency or disk for safety or recoverability. A sensible default is replication factor 3 with min.insync.replicas=2 and acks=all, enough partitions for twice your peak, and at-least-once delivery with idempotent consumers. Change one of them only when you can name what you are buying.

Watch for

Common mistakes

  • Committing the offset before the work

    If the consumer commits offset 4,201 and then crashes while writing to the database, the restart begins at 4,202 and that record is never processed. This is at-most-once by accident. Commit after the side effect, and make the side effect idempotent.

  • Adding partitions to a keyed topic

    partition = hash(key) mod P, so changing P moves keys. With the page’s crc32, order-42 goes to partition 2 when P = 4 and to partition 4 when P = 6. Its new events now sit in a different partition from its old ones, and per-key order is gone across the change.

  • <code>acks=all</code> with <code>min.insync.replicas=1</code>

    acks=all means “all in-sync replicas”. If followers fall behind, the ISR shrinks to the leader alone, and acks=all quietly behaves like acks=1. Set min.insync.replicas=2 so the producer gets an error instead of a false guarantee.

  • Slow work inside the poll loop

    If processing one batch takes longer than max.poll.interval.ms (5 minutes by default), the consumer is treated as failed, leaves the group, and its partitions are rebalanced. The batch is processed again elsewhere, which can take as long and trigger the next rebalance. Use smaller batches, or hand the work off and pause the partition.

  • A key with a few huge values

    Keying by tenant or country puts the biggest tenant on one partition. One consumer then has to keep up with all of that tenant’s traffic, and adding consumers does not help. Key by the narrowest thing that must stay ordered, such as an order id rather than a merchant.

In the wild

Where this shows up in production and interviews

  • Change data capture

    Tools such as Debezium read a database’s change log and publish each row change to Kafka, keyed by primary key. Search indexes, caches and warehouses all consume the same topic, which is the many-readers case from section 01.

  • Stream processing state

    Kafka Streams backs its local state stores with changelog topics, compacted for key-value stores. When an instance dies, its replacement rebuilds the state by reading that topic. Section 07’s “rebuildable source of truth” is the recovery mechanism here.

  • Lag is the health metric

    Teams alert on consumer-group lag, not broker CPU. Lag that rises and falls is normal. Lag that only rises means consume is slower than produce, and the drain formula says it will never catch up.

  • The interview version

    In “design a news feed, metrics pipeline or ad-click counter”, say the partition key and what it orders. Do the step 1 to 5 arithmetic aloud, state at-least-once with idempotent consumers, and say what happens when one key goes hot. That covers what most interviewers probe.

Self-check

Check yourself

A topic has 12 partitions and a group of 16 consumers at 4,000 records/s each. Producers write 50,000/s. Does lag drain?

No. Only min(12, 16) = 12 consumers work, which gives 48,000/s, less than 50,000/s produced. The 4 extra consumers are idle. You need at least 13 partitions (50,000 ÷ 4,000 rounded up) or faster consumers.

Payment events for one account must be applied in order. You key by <code>payment_id</code>. What breaks?

Each payment id hashes on its own, so one account’s payments spread across partitions, where there is no relative order. A refund can be applied before its charge. Key by account_id so every event for the account shares one partition.

With <code>acks=1</code>, the leader acknowledges a write and dies before any follower copies it. What happens to the record?

It is lost. A follower without the record becomes leader, and the producer already counted it as sent. With acks=all and min.insync.replicas=2, the ack waits until a second replica has it.

A new service needs every user’s current profile. Should the profile topic use 7-day retention or compaction?

Compaction. With 7-day retention, a user who has not changed their profile in 8 days has no record left. A compacted topic keeps the latest value per key forever, so the new service reads from offset 0 and gets a complete snapshot.

Frequently asked

Quick answers

What is Kafka?

A distributed, append-only commit log for event streams. Producers append records to partitioned topics; consumers read forward by offset. Records are retained and replayable, and many independent consumer groups can each read the whole stream.

Partitions and offsets?

A topic is split into partitions, each an ordered append-only log; every record has an offset (its position). Partitions are the unit of ordering and parallelism; consumers track an offset per partition.

How do consumer groups scale?

Kafka assigns each partition to exactly one consumer in a group, so parallelism is capped by partition count. Different groups are independent and each get the full stream.

Does Kafka guarantee ordering?

Only within a partition. Give related records the same partition key so they land in the same partition and stay ordered; records with different keys have no cross-partition ordering.

Finished this one? 0 / 209 Handbooks done
NextKafka vs RabbitMQ Next on the “Moving data between services” ladder · rung 2 of 6

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Handbooks