Kafka
Read first: Queues and logs, Partitioning and sharding
A topic is split into partitions, and a key stays on one partition, which is the only order you get. A consumer group assigns those partitions to members, a rebalance moves them, and lag is how you see a member fall behind. acks all means the in-sync replicas have stored the record while a consumer may still be behind, and the idempotent producer stops duplicate appends only inside that protocol.
Queues and logs separated work from facts. Kafka is a replicated, partitioned log for the facts, built so more than one independent reader can tail the same history. It came out of LinkedIn. Jay Kreps, Neha Narkhede, and Jun Rao wrote down the design. You do not need their paper memorized. You need to be able to redraw a topic, say what a key does to order, and say what a dead consumer actually loses.
Core concepts
A topic is a named log. Producers append records. A record has a key, a value, and a timestamp. The broker assigns the offset, which is the position of that record inside one partition. Offsets increase as records are appended. Clients do not pick them. When someone says “the message id,” ask whether they mean a key they generated or an offset the broker assigned. Those are different objects. The offset orders the partition. The key decides which partition you land on.
A partition is the unit that matters. It is the unit of order, of parallelism, and of replication. Inside one partition, records are totally ordered by offset. Across partitions, there is no order you can promise. A topic with 12 partitions is 12 independent logs that share a name. You add partitions to add parallelism. You do not add them to make one hot key faster. Partitioning and sharding is the same lesson in database clothes: a hash spreads load and kills cross-key range scans, a hot key is not cured by more partitions, and changing the partition count moves keys.
The key is how you buy order. Records with the same key go to the same partition, so one user’s clicks are ordered relative to each other. Two users are not ordered relative to each other, even if one click “obviously” happened first, because they can sit on different partitions and those partitions do not share a clock that the consumer is allowed to treat as a total order. If you omit the key, the producer may place each record on any partition. Two clicks from the same user can then land apart, and any order you thought you had is gone. Pick the key from the entity that must stay ordered. User id for clicks. Account id for balance events. Do not pick a key that is unique per event if you also wanted per-user order. A unique key spreads beautifully and orders nothing.
A consumer group is the competing-consumer idea, lifted to partitions. Members of one group split the partitions. Each partition is assigned to one member. A member with several partitions reads them all. If you have more members than partitions, the extras sit idle. They do not steal a partition, and they do not split one. Parallelism of a group tops out at the partition count. Two different groups do not compete. The click counter is one group. The archiver is another. Both read every record, each at its own offset. That is the log’s independent readers, and it is the opposite of putting both jobs on one queue.
Rebalance moves partitions. The group membership changes when a member joins, leaves, dies, or when the partition count changes. The group then computes a new assignment. Partitions move from the dead member to the living ones. Until that assignment settles, the moved partitions are not being read, so the tip of the log runs away from the committed offset and lag climbs. After the move, the new owner starts at the last committed offset, not at the last record the dead process happened to have in memory. Anything fetched and not committed is read again. Anything committed is not.
The leader and the ISR. Each partition has a leader. Producers append to the leader. Followers replicate by tailing it. The in-sync replicas, the ISR, are the leader plus the followers that have caught up closely enough to be eligible to take over. A follower that has fallen behind drops out of the ISR until it catches up. This is Replication with the log as the data: synchronous enough to wait for the ISR, asynchronous enough that a follower outside that set does not slow the write. If the leader dies, a new leader is chosen from the ISR, so the new leader has the records the old one considered durable under acks all.
acks is whose disk you waited for. It is not a consumer ack.
- Waiting for nobody is send-and-forget. The produce call can return before any broker has the record. A crash loses clicks the producer may already have counted as sent.
- Waiting for the leader stores the record on the leader. A leader failure before followers catch up loses the tail, the same tail loss as asynchronous replication.
acksall waits until the current ISR has the record. The click counter may still be minutes behind. Durability here means “a new leader from the ISR will have it.” It does not mean “every replica that has ever existed has it,” and it does not mean “a consumer applied it.”
Retention and compaction are two different ways to forget. Retention by time or by size drops the old end of the partition. The history before the cutoff is gone for everyone. Compaction keeps the latest record for each key and drops the older ones. A topic of raw clicks must not be compacted if you still need every click. Compaction would leave you the last click per user and throw away the session. A topic that means “the current email address of user 17” should be compacted, because the older addresses are not the current fact. Compaction is a retention policy for a changelog, not a compression codec. You can also fill a size cap during a spike and discover that “seven days” silently became “thirty hours.” If consumers were promised a week of replay, the contract has to be time, with size only as a backstop you alarm on.
Lag is the signal. For one partition, lag is the tip offset minus the group’s committed offset. Sum across partitions for the group. A queue nags you with per-message acks and a depth. A log does not ack each business effect back to the producer. The consumer’s pointer is the whole story. A member can be alive, heartbeating, and still falling behind. Lag that climbs while the process looks healthy is a slow handler or a hot partition. Lag that climbs because the committed offset froze, while the process is gone, is a dead consumer and then a rebalance. Alert on lag growth. Do not alert only on process liveness.
The idempotent producer is a bounded claim. A producer retry after a timeout has an ugly ambiguity: the broker may have appended the batch and lost the response. A naive retry appends a second copy. The idempotent producer gives that producer a identity and a sequence on the partition, and the broker rejects a sequence it has already accepted. Retries do not create a second copy of the same batch in the log. That is the bound. It is inside Kafka’s protocol, for that producer. It does not dedupe a consumer that writes a database. It does not dedupe an email. It does not dedupe a card charge. It does not repair a consumer that committed late and therefore reprocessed a batch. Those are Delivery guarantees and Idempotency and the exactly-once myth. Kafka transactions can commit consumed offsets and produced records together, still inside Kafka. The moment the effect leaves that protocol, the claim stops.
Producers batch. A batch is a group of records sent as one append. Throughput goes up and the per-record broker cost goes down. The record at the front of the batch waits for the batch to fill or for the producer to give up waiting. That wait is a latency choice. At a low rate it buys you almost nothing. The worked example does the arithmetic so you do not turn it on by superstition.
A worked example
You are recording click events. The key is the user id. One user stays on one partition, so that user’s clicks stay in order. A consumer group counts them and writes aggregates. Then one consumer dies.
Assumptions:
- 20 million click events a day. A sketch for this design, not a measured workload from a named company.
- An average record is 200 bytes.
- The topic has 12 partitions and 3 replicas.
- The peak is 3 times the average. An assumption.
- The counting group has 3 members, so each owns 4 partitions while everyone is alive.
- When a member dies, the group spends 30 seconds moving partitions before the new owners are reading. An assumption about this incident, not a default timeout you should quote as law.
- The dead member had been committing offsets every 5 seconds. An assumption.
- A bot, or a badly chosen key, accounts for 30 percent of clicks and hashes to one partition. A second assumption, for the hot-key case. A healthy user-keyed stream is much flatter. Measure before you believe the 30 percent.
average rate
20,000,000 / 86,400 = 231.5 clicks per second
shortcut: 20,000,000 / 100,000 = 200 per second
peak, assumed 3x
231.5 * 3 = 694 per second
even spread across 12 partitions
average 231.5 / 12 = 19.3 per second
peak 694 / 12 = 57.8 per second
hot key at 30 percent, one partition
average 0.30 * 231.5 = 69.4 from the bot alone
the other 70 percent spread over 12 partitions is about 13.5 each
the hot partition is about 69.4 + 13.5 = 83 per second average
and about 250 per second at the peak
dead consumer owned 4 of 12, even traffic
4/12 * 231.5 = 77.2 per second not being read
30 seconds of rebalance: 77.2 * 30 = about 2,300 records of lag
5 seconds uncommitted: 77.2 * 5 = about 386 records read again
storage
20,000,000 * 200 bytes = 4 GB per day, one copy
7 days * 3 replicas = 21 times one day
21 * 4 GB = 84 GB
A day is 86,400 seconds. The shortcut of 100,000 is about 16 percent low here, which is fine when you say “about 200 a second,” and too coarse when you are sizing the hot partition. Use the real divisor once you are comparing two designs that are close.
The 386 records are the part people blame on the wrong component. The idempotent producer did its job on the way in. Those clicks exist once in the partition. The dead consumer had fetched them, had not committed the offset, and died. The new owner reads them again. If the counter is total = total + 1 for each record, those 386 clicks are counted twice. If the counter’s sink stores the event id and ignores one it has seen, they are counted once. The producer feature never sees that choice. It lives on the read side.
Lag during those 30 seconds climbs by about 2,300 records and then falls as the survivors catch up, provided the survivors are fast enough to read their new partitions and their old ones. They just went from 4 partitions to 6 each. At an even 19.3 per second that is 116 per second of reading per survivor, plus the catch-up burst. If the handler was already near its limit, the rebalance does not just pause. It leaves a permanent slope until you add partitions and members together, or until you make the handler cheaper.
The hot partition does not participate in that fix. At the assumed 30 percent, one partition holds about 83 clicks a second average and about 250 at the peak. A thirteenth consumer cannot take half of it. The group assigns partitions, not keys. More partitions would reshard the mild keys and leave the bot on exactly one of the new partitions, because the key still hashes to one. A hot key is not fixed by more partitions. The fixes are to change the key so one bot can occupy several partitions on purpose, to throttle that producer, or to make one partition’s consumer fast enough for 250 a second. Adding brokers does nothing to a key.
Compaction on this topic would be a product bug. Compaction keeps the latest record per key. You would retain one click per user and delete the rest, and the daily count would collapse toward “unique clickers.” If you also want “last click per user,” that is a different topic, compacted, written by a consumer that emits the latest event. Five million users, under another assumption, at 200 bytes each, is about 1 GB one copy, not 4 GB every day. Different retention because it is a different fact.
Retention of 7 days is why the 84 GB exists. It is also a deadline. A consumer that is down for 8 days cannot rebuild Monday from this topic. The offsets it wanted have been deleted. Lag is not an IOU that survives retention. If the count is something you bill from, 7 days is either enough for the outage you will actually notice, or you export the log somewhere cheaper before the cutoff.
Batching, so the linger is a decision and not a default you copied:
20 million a day, linger 10 ms, assumed
231.5 * 0.010 = about 2 records per batch
same linger at the 2-billion-actions-a-day sketch
2e9 / 86,400 = about 23,100 per second
23,100 * 0.010 = about 230 records per batch
Dean's same-datacenter round trip is 0.5 ms
10 ms of linger is 20 of those round trips
At 231 a second you waited 10 ms to group a pair of clicks. A round trip inside one datacenter, on Dean’s teaching list, is half a millisecond, so the linger dominates the produce latency and buys almost no coalescing. At the estimation sketch of 2 billion actions a day, about 20,000 a second by the 100,000-second shortcut and about 23,100 with 86,400, the same linger groups a few hundred records and is a real throughput tool. Batch because the produce rate makes the request overhead matter. Do not batch a quiet topic into a slower one out of habit. The 2 billion figure is that sketch, 100 million people times 20 actions, not this click product’s traffic.
flowchart LR
clicks[Click service] --> p0[Partition 0]
clicks --> p1[Partition 1]
clicks --> p2[Partition 2]
p0 --> live[Live consumer]
p1 --> dead[Dead consumer]
p2 --> live
User A and user B stay ordered only because each key sticks to one of those partitions. The dead consumer’s partitions are the ones whose offsets freeze until rebalance. The live consumer does not pick up the work by being helpful. The group has to assign it.
flowchart LR
producer[Producer] --> leader[Partition leader]
leader --> syncA[In sync replica A]
leader --> syncB[In sync replica B]
leader --> behind[Replica still catching up]
acks all returns when the leader and the in-sync replicas have the record. The replica that is still catching up is not in that wait. A consumer is not in the picture at all. If you tell a product manager that acks all means the click has been counted, you have lied. You mean the log has a durable copy. Lag tells you about the count.
Tradeoffs
| Choice | What you gain | What you spend |
|---|---|---|
| More partitions | More members can do useful work, and a single dead member owns a smaller fraction | More open files and more rebalance work, and you must not change the count casually because keys move |
| Key by user id | One user’s clicks stay ordered on one partition | A hot user is a hot partition you cannot split without changing the key |
| No key | Even spread, simple producers | No per-user order, so a consumer cannot assume it saw a session in order |
acks all |
An acknowledged write survives leader loss, as long as the new leader comes from the ISR | Produce latency tracks the slowest in-sync replica |
| Wait only for the leader | A faster produce call | Failover can lose acknowledged clicks, the async-replication tail |
| Retain by time | A promise you can explain, “seven days of replay” | Bytes, and a hard cliff when a consumer exceeds it |
| Compact | The latest value per key, small topics for current state | You destroy history. Wrong policy for raw events |
| Commit offsets often | Less duplicate work after a crash | More broker chatter, and a commit that runs ahead of the effect skips records |
| Idempotent producer | Producer retries do not double-append | Nothing for consumer retries, email, or charges. The bound is the log |
Changing the partition count is the tradeoff people skip. The mapping from key to partition is a modulo of a hash in the ordinary case, and modulo hashing moves almost every key when the modulus changes. After you go from 12 partitions to 24, user 17’s new clicks land on a new partition, while their old clicks are still on the old one. Order across the change does not exist. Either you accept a seam at migration time, or you write a new topic and cut readers over. “We will add partitions during the launch” is a reorder of every key.
Pitfalls
- Using a unique event id as the record key. Spread is perfect. One user’s clicks are scattered, and any consumer that assumed per-user order is wrong. Symptom: sessions that start before they end, in the consumer’s view. Key by user, and keep the event id in the value for dedupe.
- Reading
acksall as “the subscriber handled it.” Symptom: the producer dashboard is green during a consumer outage, and the product is missing a day of counts. Pair produce success with consumer lag. - Committing the offset on a timer, ahead of the database write. That is an ack before the effect. Symptom: a crash skips a slice of clicks, the lag looks fine, and the total is low. Commit after the sink accepts the batch, or commit the offset in the same transaction as the sink write.
- Compacting a click stream. Symptom: counts drift toward uniques as the compactor runs, and older clicks vanish while retention time has not elapsed. Compaction is not “save disk.” It is “keep last write per key.”
- Adding consumers without adding partitions. The new process uses CPU doing nothing. Symptom: a fourth member on a 3-partition topic, idle, while lag on the hot partition grows. Look at assigned partitions, not at replica count of the process.
- Treating a rebalance blip as data loss. The 2,300-record climb in the example is unread data, still in the log. The 386 are duplicate reads, not lost writes. The failure mode that loses data is a commit that ran ahead, a retention cliff, or a leader change onto a replica that did not have the tail.
- One consumer group for two products. The archiver and the counter then split partitions. Each misses the partitions the other was assigned. Separate groups. They are cheap compared to a wrong total.
- Ignoring the hot key because the average partition looks fine. Average of 19 a second hides a partition at 83. Alert on the max lag of any partition. A sum can hide one hot partition.
In the interview
Draw the topic before you name a feature. “Clicks are a topic keyed by user id, so order is per user, per partition. Twelve partitions, a consumer group for the counter, a second group for the archive. Producers wait for the ISR. I alert on lag. Retention is seven days, not compaction, because I need every click.” That is a full answer for the first five minutes.
Put a number on it. Daily volume over 86,400, divided by partitions, and then say what a single hot key does to that average. The bottleneck is the hottest partition’s consumer, not the cluster in the abstract. The tradeoff worth saying out loud: acks all costs produce latency and buys durability of the log, and it still says nothing about the counter. The idempotent producer belongs in the same breath as its bound, or you should leave it out. “It stops duplicate appends on producer retry. The consumer is still at-least-once.”
Skip a config-key recital. Skip the history of the metadata store. Skip a claim of end-to-end exactly-once. If the interviewer asks what happens when a consumer dies, walk the example: committed offset, rebalance, reprocessing of the uncommitted tail, idempotent sink. If they ask what happens when the leader dies, walk the ISR. Those two crashes are the ones that distinguish a diagram from a design.
Check yourself
Clicks are keyed by user id. What order can a consumer rely on, and what order can it not?
One user’s clicks share a partition, so that user’s records arrive in offset order. Two users can sit on different partitions, and those partitions are not ordered against each other. A consumer that merges them has to use the event timestamp if it cares, and that timestamp is not a total order of the topic. Omit the key and you lose even the per-user promise, because the producer may then place records anywhere.
A topic has 12 partitions and the group has 15 members. Why are some members idle? What does a dead member do to lag?
A partition is assigned to one member, so three members get nothing. They will not help the hot partition. When a member dies, its partitions are not read until rebalance assigns them, and the new owner starts at the last committed offset. Lag climbs for the length of that pause at the produce rate of those partitions, and any batch already fetched but not committed is processed again.
The producer got an acknowledgement from acks all. Has the click counter applied the record?
No. The ISR has stored it. That is a statement about replicas of the log, not about any consumer group. The counter applies the record when it reads it and commits its own offset. Until then the record is durable and uncounted. Lag is the gap between those two facts.
Why is the idempotent producer not the thing that saves you from double-counting after the dead consumer?
The idempotent producer rejects a retried append so the log contains one copy of a batch. The dead consumer’s duplicates come from reading that one copy twice, because the offset was not committed. Deduping the count is a sink problem: store the event id, or commit the offset in the same transaction as the increment. The producer’s sequence number never sees the sink.
You compact the raw click topic to save disk. What is left of a user who clicked fifty times?
One record, the latest one for that key. Compaction keeps the last record per key and drops the older ones. The other forty-nine clicks are gone even if time retention has not elapsed. Current-state topics are the ones to compact. A click history needs time or size retention, or an export, not compaction.
Based on: Jay Kreps, Neha Narkhede, and Jun Rao; Designing Data-Intensive Applications, Kleppmann and Riccomini.