Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
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.
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.
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.
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."
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."
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.
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:
Eight consumers on four partitions? Four work, four idle. Consume slower than you produce? Lag never drains. The runnable version below computes all three.
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
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.
Delivery semantics
How many times might a record be processed? Kafka supports three semantics, and the honest default is the middle one.
| Guarantee | Means | Cost / how |
|---|---|---|
| At-most-once | Never processed twice; may be lost | Commit offset before processing — fast, lossy |
| At-least-once | Never lost; may be processed twice | Process, then commit offset — the common default |
| Exactly-once | Processed once, no loss or dup | Idempotent 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.
"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.
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.
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.
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.
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.
| Step | Question | Arithmetic | Answer |
|---|---|---|---|
| 1 | Consumers needed at peak | 30,000 ÷ 4,000, rounded up | 8 |
| 2 | Partitions, so all 8 can work | active = min(P, C), so P ≥ 8 | at least 8 |
| 3 | Consumers go down for 10 minutes | 30,000/s × 600 s | lag = 18,000,000 records |
| 4 | Drain with 8 consumers | 18,000,000 ÷ (32,000 − 30,000) | 9,000 s = 2.5 hours |
| 5 | Drain with 16 consumers on 16 partitions | 18,000,000 ÷ (64,000 − 30,000) | ≈ 529 s, under 9 minutes |
| 6 | Disk for 7 days of retention | 10,000/s × 1 KB × 604,800 s | ≈ 6 TB of log |
| 7 | With replication factor 3 | 6.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.
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.
| Case | Time | Space | Why |
|---|---|---|---|
acks=all vs acks=1 | acks=all waits for every in-sync replica, so each write is slower | No difference in storage | acks=1 can lose the newest writes if the leader dies before followers copy them. |
Replication factor 3, min.insync.replicas=2 | One extra follower round-trip per write | 3 copies of every byte | Writes keep succeeding with one broker down, and no acked write lives on only one machine. |
| More partitions | More parallel consumers, so lag drains faster (step 5) | More files, replication streams and leader elections | You cannot easily reduce the count, and adding partitions remaps keys. |
| Time retention (7 days) | Replay any point inside the window | Grows with throughput × time | Anything older is deleted, read or not. |
| Log compaction | A new reader rebuilds state by reading from offset 0 | Grows with the number of distinct keys, not with time | Only the latest value per key is kept, so it is not an event history. |
| Exactly-once (idempotent producer + transactions) | Transaction commits add latency | Small transaction state | Covers read-process-write inside Kafka. A write to your own database still needs an idempotent handler. |
| Larger producer batches | Higher throughput, a few ms more latency per record | More producer memory | Kafka’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.
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-42goes 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=2so 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.
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.
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.
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.
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Handbooks
- Kafka vs RabbitMQThey both "move messages", which is exactly why teams pick the wrong one. Kafka is a durable, replayable log where consumers track their own offset; RabbitMQ is a smart broker that routes each message and deletes it on ack. The remember-vs-forget core difference, throughput and ordering trade-offs, and how to choose.Read →
- The WebSockets & Real-Time HandbookWhy "live" is hard on a protocol that can't push. Polling makes you wait on average half the interval to learn of an event (a 10s poll = ~5s staleness) and wastes a request every time nothing changed — and shrinking the interval only multiplies the waste. A WebSocket keeps one persistent full-duplex line open so the server pushes the instant something happens: latency ≈ one network hop, zero empty requests. The poll-vs-push latency math, when to use SSE instead, and the stateful-scaling pitfalls. With worked math and runnable code.Read →
- Kafka vs KinesisSame partitioned-log model underneath, different operational surface: Kafka is self-run and portable with a huge ecosystem; Kinesis is fully AWS-managed with a hard per-shard throughput ceiling. Retention, cost model, and the lock-in trade-off.Read →
- REST vs Webhooks vs SSEThree ways client and server move data, split by who exposes an endpoint and whether the connection stays open: REST pulls, webhooks flip who runs the server, SSE keeps one connection open for a live push. How real systems run all three at once.Read →
- Streaming vs BatchBatch processes on a schedule; streaming reacts per-event. The real engineering cost of streaming isn’t speed, it’s correctness under disorder — event time vs processing time, watermarks, exactly-once semantics. The Lambda and Kappa architectures that combine both.Read →
- AI for DoctorsThe practical middle ground for clinicians: where AI genuinely helps (notes from dictation, discharge instructions, prior auths, literature summaries), the three non-negotiable rules — PHI needs a BAA, verify everything clinical, the chart is yours — five workflow recipes with exact prompts, a spot-the-danger judgment exercise, and the six questions to ask any clinical AI vendor. No coding required.Read →