Design a Kafka-like distributed message queue - producers append records to partitioned topics, consumer groups read them at their own pace and can replay them, and no acknowledged record may be lost when a broker dies. One million messages a second have to land on ordinary disks. The staff-level signal is seeing that this is a replicated log and not a queue, saying exactly when a write counts as acknowledged, and keeping the broker so thin that the disks only do what they are good at.
Written by a Staff+ Engineer and an Engineering Manager
12+ years of experience in distributed systems and real-time messaging. Tech lead for large-scale chat applications serving billions of users. Over 12 years of industry experience with 6 years in engineering leadership, building and scaling tech infrastructure teams that deliver end-to-end large-scale distributed systems.
Finished this lesson?
Sign in to save your progress across devices.
Tip: use ← and → to move between lessons.
Was this lesson helpful?
Rehearse this exact question with the author
45-minute mock with a Staff+ engineer who interviews at your target company. Premium members save $20.
What to Design?
Could you answer these today? Tick what you already know.
The happy path is quick to draw: producers on the left, a cluster of brokers in the middle, consumers on the right. The interview is decided by four questions about what happens around that path. Each one is a deep dive later on this page, with three designs side by side: the one that sounds right, a better one, and the one that holds.
Swipe to see all columns
| The four questions, and the answer that sounds right | |||
|---|---|---|---|
| # | The interviewer asks | The answer that sounds right | What it misses |
| DD1 | The leader crashes 10 ms after it took a batch. Was the batch acknowledged? | Yes, the leader wrote it to its log | The only copy died with the leader. The producer holds an ack for records that are gone |
| DD2 | One follower is slow, then the leader dies. Who takes over? | Any follower that is alive | The slow one is 900 records behind. Promote it and acknowledged records disappear |
The same three habits answer all four:
Do not spend your questions on message formats. Spend them on what the system promises.
Swipe to see all columns
| Scope Decisions | ||
|---|---|---|
| Question | Agreed answer | Why it matters |
| Is it a queue or a log? | A log. A record stays until its retention time is over. Reading removes nothing | Replay is free and many groups can read the same data. Deleting is a background job (Phase 3) |
| What does delivery promise? | At-least-once: a record may arrive twice, but is never lost. Exactly-once is an extension | Consumers must cope with a duplicate. No transaction manager sits on the hot path |
| What is ordered? | Records inside one partition. Nothing across partitions | |
Out of scope (say this out loud): stream processing on top of the log, a schema registry, full exactly-once engineering, replication across regions, moving old data to object storage, connectors to other systems, and quotas, permissions and login.
FR1 — Publish. A producer sends records to a topic. A topic is a named stream that is split into partitions. Records with the same key always go to the same partition. Records without a key are spread evenly.
FR2 — An ordered log. Each partition is a log that only grows at the end. Every record gets an offset: its position in the partition, counted from 0. A stored record never changes.
FR3 — Consumer groups. Consumers that share a group name share the work. Each partition has exactly one owner inside a group. Different groups read the same topic independently.
FR4 — Read, replay, commit. A consumer reads from any offset that is still stored. It commits the offset it has finished, so that it can resume there after a restart.
FR5 — Replication. Every partition is kept on three brokers. A broker is one server of the cluster, and each copy is called a replica. One replica is the leader and takes all writes. The other two are followers. An acknowledged write survives the loss of any one broker.
FR6 — Retention. Records are deleted when they are older than a configured time, for example 4 days. Whether anyone has read them plays no role.
The key principle behind all six
Swipe to see all columns
| Five facts and the conclusions they do not supportRead each row as: the fact on the left does not, by itself, imply the claim in the middle. | ||
|---|---|---|
| Fact | Does not imply | Why the gap exists |
| The leader wrote the record | The record is safe | It is one copy on one machine. That machine can die a millisecond later |
NFR1 — Throughput. 1 million messages a second at peak, about 1 GB every second.
NFR2 — Latency. Under 200 ms at p99 from the producer to a consumer that is reading at the end of the log.
NFR3 — Durability. No acknowledged record is lost when any single broker fails.
NFR4 — Availability: 99.95% for writing and reading. When a leader dies, another broker takes over without a human.
NFR5 — Scale. 10,000 topics, 100,000 partitions, about 1 PB on disk.
| Capacity Thought Experiment | |
|---|---|
| Parameter | Value |
| Messages coming in | 1 million a second at peak, 1 KB each: 1 GB every second |
| Written to disk, with three copies | 3 GB every second |
| One day | 86 TB of messages, 260 TB on disk |
| Retention | 4 days: 346 TB of messages, about 1 PB on disk |
| Brokers | About 30. Each writes 100 MB a second and holds about 35 TB |
The number that identifies the real system is how often something has to happen per second:
one request per record 1,000,000 requests and disk flushes a second no disk can do this
one request per batch 10,000 requests a second (100 records each) easy
one broker 100 MB/s added at the end of files what a plain disk does best
A disk is slow when it has to confirm many small writes and fast when it writes one long stream. So the design has to turn a million small writes into a few thousand large ones, and it must still be able to say which of them are safe. Every cluster number above is an illustrative assumption.
Interviewer signal: candidates who draw "a queue service with a database behind it" have missed the number. Candidates who say "this is an append-only log: I batch on the client, append sequentially on the broker, and replicate each partition to three brokers before I acknowledge" have found the system.
Three ideas shape everything:
A classic queue hands a message to one consumer and deletes it, so it has to remember per consumer what was delivered and confirmed. A log does less. It only appends records and numbers them. A reader says "give me records from offset 7000" and keeps its own position. Reading again is the same call with a smaller number, and ten groups can read the same log.
One log on one machine is not enough for 1 GB a second. So a topic is split into partitions, and each partition is its own small log. A partition is the unit of order (one sequence of offsets), of parallel work (one owner per group), and of replication (three copies, one leader).
The broker does two things: it adds batches to the end of a file, and it sends a range of a file to whoever asks. Everything else is done by the clients. The producer chooses the partition and builds batches. The consumer pulls and remembers its position. The less the broker does per record, the more records it can take.
The core recognition
This is an append-only log, partitioned for scale and replicated for safety. Delivery guarantees, consumer groups, replay and recovery all follow from that one data structure. Do not start with retry settings. Start with the log.
| Design Decisions | |
|---|---|
| Design choice | Reason |
| Records are appended to a log and never deleted on read | Replay and many independent groups cost nothing extra |
| A topic is split into partitions, and a key picks the partition | Order per key, and parallel reads and writes |
One structure carries the design: the log of a partition. Learn its three positions first. Everything else is small bookkeeping around it.
Swipe to see all columns
| Three positions in every partition | ||
|---|---|---|
| Position | Meaning | In our example |
| Log start offset | The oldest record that is still stored. It moves up when retention deletes a segment | 0, later 2000 |
| High watermark | Everything below it is on every in-sync copy. Consumers read only below it | 7000, then 7100 |
| Log end offset | The offset the next record will get | 7000, then 7100 |
Each replica keeps the log as a folder of segment files. A segment is one slice of the log, about 1 GB. Only the newest segment is written to. The others are closed and never change.
Swipe to see all columns
| Files of one segment | ||
|---|---|---|
| File | Content | Comment |
.log | The record batches, one after the other | A batch carries its first offset, the producer id, a sequence number and the records: key, value, timestamp |
.index | Offset to byte position | Sparse: one entry every few KB. Small enough to stay in memory |
.timeindex | Timestamp to offset | |
Kept by the controller, which is a small group of three servers that agree on every change.
Swipe to see all columns
| partition state | ||
|---|---|---|
| Field | Type | Comment |
topic, partition | STRING, INT | For example orders, 0. Written as orders-0 on this page |
replicas | LIST | |
How far a group has processed a partition. It is stored as a record in an internal topic called consumer_offsets, so it is replicated like everything else.
Swipe to see all columns
| consumer_offsets | ||
|---|---|---|
| Field | Type | Comment |
group, topic, partition | STRING, STRING, INT | The key: billing, orders, 0 |
offset | ||
Swipe to see all columns
| Supporting records | ||
|---|---|---|
| Record | What it holds | Why it exists |
| Topic | Name, number of partitions, copies per partition, retention time | Set when the topic is created |
| Group | Members, who owns which partition, a generation number | Kept by the group coordinator, the broker that looks after this group. Changes at every rebalance (DD3) |
| Broker | Id, rack, last heartbeat | The controller uses it to notice a dead broker (Phase 4) |
Swipe to see all columns
| Storage | ||
|---|---|---|
| Store | Data | Consistency |
| Broker disks | Segment files of every partition | The leader's log decides. Followers copy it |
| Controller quorum | Topics, leaders, epochs, in-sync sets | Strong. Three servers agree before a change counts |
Topic consumer_offsets | Committed offsets of every group | Replicated like any topic |
Clients do not speak REST to a broker. They use a compact binary protocol over long-lived TCP connections, because parsing a million JSON requests a second would waste the CPU. There are only a handful of calls.
Swipe to see all columns
| The broker protocol | ||
|---|---|---|
| Call | Request | Response |
Metadata | Topic names | For each partition: the leader and the replicas. Clients cache it and ask again after an error |
Produce | Topic, partition, acks, a batch of records, producer id, sequence number | base_offset, the first offset of the batch. Or NOT_LEADER_FOR_PARTITION |
acks is the producer's choice of when a write counts as done: 0 means do not wait, 1 means the leader has it, all means every in-sync copy has it (DD1).
Why pull and not push. A broker that pushes has to know every consumer, its speed, and what it has confirmed. With pull, a slow consumer simply asks less often, and a replay is a fetch with an older offset. To avoid empty answers, the broker holds a fetch for up to max_wait_ms and answers as soon as there is data.
Present the design as four short stories, each in its own colour on one whiteboard: Phase 1 produce (black), Phase 2 consume (blue), Phase 3 replay and retention (green), Phase 4 leader failover (purple). Every story has six numbered steps. The number on an arrow is the same number in the animation and in the step table.
Swipe to see all columns
| The four phases | |||
|---|---|---|---|
| Phase | Colour | Story | What it leaves behind |
| Phase 1: Produce (FR1, FR2, FR5) | Black | The checkout service publishes 100 order records | Offsets 7000 to 7099 on three brokers. High watermark 7100 |
| Phase 2: Consume (FR3, FR4) | Blue | The consumer billing-1 reads them and commits | The group billing is at offset 7100 |
How to read the picture
orders-0, which is partition 0 of the topic orders. Broker 1 leads it. Brokers 2 and 3 follow.Each phase below is an interactive walkthrough of the same picture. It plays on its own. You can pause it, step with the arrow keys, and click any component to read its role.
Goal: get a batch into the log in order, and acknowledge it only when three brokers have it.
Metadata(orders)Producer → Broker 16 partitions. orders-0: leader Broker 1Nothing is written in this step.
Swipe to see all columns
| Phase 1 step by step (black arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | The producer asks any broker: Metadata(orders). The answer: six partitions, and Broker 1 leads orders-0. The producer caches this. | Nothing |
| 2 | The key user-42 hashes to partition 0. The producer collects records for orders-0 | |
Why it is built this way
Because two brokers would both hand out offset 7000. Each would put its own record there, and the copies would no longer be the same log. With one leader there is one place that gives out offsets, so there is one order. The price is that all writes to a partition go through one machine. The answer to that is more partitions, not more leaders.
The topic orders has six partitions. The producer picks one for every record: the hash of the key, modulo 6.
Swipe to see all columns
| Three records, two keys | |||
|---|---|---|---|
| Record | Key | Partition | Order |
| order 9001 placed | user-42 | orders-0 | First for user-42 |
| order 9002 placed | user-7 | ||
Everything about one user is in one partition and stays in order. Records of different users may be read in any order, and that is what lets six consumers work at the same time. Pick as the key the thing whose events must stay in order.
Goal: let a consumer read at its own pace, and remember how far it got in a place that survives a crash.
JoinGroup(billing), then SyncGroupConsumer billing-1 → Group coordinatorbilling-1 owns orders-0, orders-1, orders-2billing-1new rowSwipe to see all columns
| Phase 2 step by step (blue arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | billing-1 joins the group billing at the group coordinator: JoinGroup, then SyncGroup. It is given orders-0, orders-1 and orders-2 | |
Why it is built this way
It never committed, so the group is still at 7000. The coordinator gives orders-0 to another consumer, which starts at 7000 and bills all 100 orders, including the 60 that were already billed. That is why the billing code must be safe to run twice, for example by storing the order id and skipping an order it has seen.
Goal: let anyone read old data with the same call, and delete old data cheaply without asking anyone.
ListOffsets(orders-0, yesterday 09:00)Consumer analytics-1 → Broker 1offset 2600yesterday 09:00read onlySwipe to see all columns
| Phase 3 step by step (green arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | A new group analytics wants yesterday's orders. analytics-1 asks Broker 1: ListOffsets(orders-0, yesterday 09:00). The time index says offset 2600. | Nothing |
| 2 | It sends Fetch(orders-0, offset 2600) | |
The example uses small segments of 2,000 records to keep the numbers readable. A real segment is about 1 GB.
Why it is built this way
OFFSET_OUT_OF_RANGE. Watch how far each group is behind.Old records sit at the front of the file. Removing the front of one huge file means writing the rest of it again, which is terabytes of work for nothing. With segments, the oldest slice is its own file, and deleting a file is cheap. Closed segments also never change, so they are easy to copy and to move to cheaper storage later.
Goal: when the leader dies, hand the partition to a copy that has every acknowledged record, and let the clients find it by themselves.
HeartbeatBrokers 1, 2, 3 → Controller quorumNothing is written in this step.
Swipe to see all columns
| Phase 4 step by step (purple arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | Every broker sends a heartbeat to the controller every 2 seconds. | Controller: last heartbeat per broker |
| 2 | Broker 1 is silent for 6 seconds. The controller marks it dead. | Broker 1: dead |
| 3 | The controller picks a new leader for orders-0 | |
A broker that is alive but no longer the leader answers NOT_LEADER_FOR_PARTITION. The client reacts in the same way: ask for the metadata again, then retry.
Why it is built this way
A short limit reacts faster and is wrong more often. A broker that only pauses for two seconds would be declared dead, and 3,300 partitions would move away and back for nothing. A longer limit costs a few seconds when a broker really dies. In those seconds producers keep their batches and retry, so the price is delay, not loss. Name the trade-off and pick a number.
The deep dives are the four questions from the top of the page. Each one compares three designs for the same scenario: a Bad one, which is usually the answer that sounds right; a Good one, which still leaves a gap; and a Great one, which holds. The answers start covered. Read the scenario, decide what you would build, then click each card.
Swipe to see all columns
| Deep Dive Map | |||
|---|---|---|---|
| Deep Dive | Topic | Scenario | NFR |
Scenario: Broker 1 takes the batch with offsets 7000 to 7099. It dies 10 ms later, before Brokers 2 and 3 have fetched the batch. What was the producer told? And where are the 100 orders now?
Three ways to build it. Decide what you would do first. The answers are covered: click a card to reveal it.
The idea. The producer sends the batch and does not wait for an answer. Nothing is faster.
Where it breaks. For the producer, sent means written. It frees the batch from its buffer at once. Broker 1 dies, Broker 2 becomes the leader, and its log ends at 7000. The 100 orders are gone and nobody ever finds out.
The idea. The leader adds the batch to its log and answers at once: base_offset 7000.
What it fixes. The producer now learns about a broker that is down or a request that never arrived, and it can retry.
What it still misses. The ack says "one machine has it". Broker 1 dies before the followers fetch. Broker 2 becomes the leader with a log that ends at 7000. The producer holds an ack for records that no longer exist, and the next batch gets the offsets 7000 to 7099 again. The window is small, a few milliseconds of records, but the loss is silent.
The key idea. An ack must mean "this survives the loss of the leader". So the leader answers only when the high watermark has passed the batch. And a retry must not create a second copy, so every batch carries a number.
How it works
acks=all, its producer id 77 and the sequence number 120.base_offset 7000.The three designs side by side, in one picture:
Play the three options. Switch between them with the tabs at the top of the figure.
Produce(orders-0, acks=0)Producer → Broker 1Nothing is written in this step.
Swipe to see all columns
| DD1 side by side | |||
|---|---|---|---|
| Bad: acks=0 | Good: acks=1 | Great: acks=all | |
| What the ack means | There is no ack | The leader has it | Every in-sync copy has it |
| The leader dies before the followers fetch | Lost, and nobody knows | Lost, although it was acknowledged | Not acknowledged yet. The producer retries |
Check it against the scenario
| Broker 1 dies around the batch | |
|---|---|
| Situation | Outcome with the Great option |
| The leader dies before the ack | The producer has no ack and still has the batch. It retries on the new leader. Nothing is lost |
| The leader dies after the ack | The new leader comes from the in-sync set, and every in-sync copy has the batch |
| The retry reaches a broker that already has the batch | Producer id 77 and sequence 120 are known. The broker answers 7000 and adds nothing |
| The ack is lost on the network | The same retry, the same answer |
| A consumer during those milliseconds | |
The trade-off to name. acks=all adds one round of follower fetches to every write, and the producer must keep a batch until its ack arrives. That costs a few milliseconds and some memory. For orders that is cheap. For click counters, acks=1 may be the honest choice.
One. Without sequence numbers there would be two: the broker cannot tell a retry from a new batch with the same content. With them, the leader knows the last sequence number of every producer. That knowledge is part of the log, so a new leader has it too.
"I define acknowledged as: every in-sync replica has the record. The producer sends with acks=all. The leader appends, the followers fetch, the high watermark moves past the batch, and only then the leader answers. If the leader dies before that, the producer never got an ack, so it retries against the new leader. To keep a retry from writing the batch twice, each batch carries a producer id and a sequence number, and the broker drops a batch it has already stored. acks=1 is faster but can lose acknowledged records when the leader dies, so I offer it only for data that may be lost."
Follow-up: "Is that exactly-once?" — It is exactly-once for one producer writing to one partition. What a consumer does with a record afterwards is a separate question (see the follow-ups).
Scenario: At 10:00 the disk of Broker 3 gets slow. Broker 3 falls behind: its log ends at 6200 while the leader's log ends at 7100. At 10:05 Broker 1, the leader, dies. Do writes wait for the slow broker? And who becomes the leader?
Three ways to build it. Decide what you would do first. The answers are covered: click a card to reveal it.
The idea. A write is acknowledged when all three replicas have it. Then every replica has everything, and any of them can become the leader.
Where it breaks. From 10:00 on, every ack waits for Broker 3. A write that took 5 ms now takes seconds. The producers' buffers fill up and their requests time out after 30 seconds. All three brokers are alive, and still the partition is as slow as its slowest disk.
The idea. The leader keeps a list of the replicas that are keeping up: the in-sync replicas, or ISR. A follower that is behind for 10 seconds is taken off the list. The ack waits only for the replicas on it.
What it fixes. Speed. Broker 3 leaves the list, and writes are fast again with Brokers 1 and 2.
What it still misses. Nobody said what the list means for an election. At 10:05 Broker 1 dies and the controller promotes a follower that is alive. It picks Broker 3, whose log ends at 6200. Offsets 6200 to 7099 were acknowledged and are gone: 900 records. Broker 2 had them, and it now has to cut its own log back to 6200 to follow the new leader.
The key idea. Once the leader stops waiting for a slow replica, that replica must never lead. And the list must not shrink to the leader alone, or "every in-sync copy" quietly becomes "one copy".
How it works
min.insync.replicas = 2. With two in-sync copies, writes go on.acks=all writes with . The producers keep their batches and retry.The three designs side by side, in one picture:
Play the three options. Switch between them with the tabs at the top of the figure.
Fetch(orders-0, from 6200)Broker 3 → Broker 1Nothing is written in this step.
Swipe to see all columns
| DD2 side by side | |||
|---|---|---|---|
| Bad: wait for all three | Good: wait for the in-sync ones | Great: in-sync set with a floor | |
| Broker 3 is slow | Every write waits for it | It leaves the set. Writes stay fast | It leaves the set. Writes stay fast |
| Who may become the leader | Anyone, all have everything | Anyone alive, also Broker 3 | Only a member of the in-sync set |
Check it against the scenario
| 10:00 to 10:06 with the Great option | |
|---|---|
| Situation | Outcome with the Great option |
| 10:00 Broker 3 is slow | After 10 seconds it is out of the in-sync set. Writes keep their speed |
| 10:05 Broker 1 dies | After 6 seconds of silence the controller makes Broker 2 the leader. Every acknowledged record is there |
| Broker 2 is the only in-sync copy | acks=all writes are refused. The producers know, keep their batches and retry |
| Broker 3 catches up | It rejoins the set and writes resume |
The trade-off to name. With a floor of two, losing two of three brokers stops the writes to their partitions. That is a choice: stop writing rather than accept writes that one more failure would destroy. A floor of one keeps writing and takes that risk.
That works too, and some systems do it. With a majority, three copies survive one failure, and to survive two you need five copies. With an in-sync set, three copies in sync survive two failures, because every member has every acknowledged record. On 1 PB of data, two extra copies are a real cost. The price of the in-sync set is the extra component that keeps the list and decides elections: the controller.
"The leader tracks the in-sync replicas: the followers that have kept up within about ten seconds. With acks=all a write waits for exactly that set, so one slow disk cannot stall the partition. Two rules make this safe. First, min.insync.replicas is 2: if the set shrinks to the leader alone, the leader rejects acks=all writes instead of acknowledging records that exist once. Second, the controller elects leaders only from the in-sync set, so a new leader always has every acknowledged record. If no in-sync replica is alive, the partition waits. Unclean election stays off."
Follow-up: "The old leader comes back and still thinks it leads?" — Its epoch is older. Followers and the controller ignore it, it cuts its log back to match the new leader, and it starts to follow.
Scenario: The group billing has three consumers and six partitions, two each. A deploy restarts billing-3: it leaves and comes back 10 seconds later. In production it is 50 consumers, restarted one after the other: 100 changes of membership in about 8 minutes. Every change starts a rebalance: the group decides again who owns which partition.
Three ways to build it. Decide what you would do first. The answers are covered: click a card to reveal it.
The idea. When the membership changes, every consumer gives up all its partitions and joins again. The coordinator hands out a fresh assignment.
Where it breaks. Nobody processes anything until the new assignment is out: about 3 seconds for all six partitions. The fresh assignment also moves partitions whose owner never left: billing-1 gets P0, P1, P2 and billing-2 gets P3, P4, P5, so P2 changes hands for no reason. Then billing-3 returns and it all happens again. With 50 consumers that is 100 full stops in 8 minutes, about 5 minutes with no processing at all.
The idea. Each member tells the coordinator what it owned before. The new assignment changes as little as possible: billing-1 keeps P0, P1 and gets P4. billing-2 keeps P2, P3 and gets P5.
What it fixes. Only P4 and P5 change owner. Caches and local state for the other four stay useful.
What it still misses. The protocol is the same. Everyone still gives up everything first, so all six partitions stand still for about 3 seconds, 100 times.
The key idea. A consumer keeps its partitions during a rebalance and gives up only the ones it is told to give up. Partitions that do not move never stop.
How it works
billing-3 stops. The coordinator starts a rebalance.billing-1 and billing-2 join again and keep fetching P0 to P3 while they do.billing-1 and billing-2, which start them at the committed offsets.The three designs side by side, in one picture:
Play the three options. Switch between them with the tabs at the top of the figure.
LeaveGroup(billing)billing-3 → Group coordinatorbilling-3deleteSwipe to see all columns
| DD3 side by side | |||
|---|---|---|---|
| Bad: eager | Good: sticky | Great: cooperative | |
| Partitions that pause when billing-3 leaves | All six | All six | Only P4 and P5, until they have a new owner |
| Partitions that change owner | P2, P4, P5 | P4, P5 | P4, P5 |
Check it against the scenario
| A rolling deploy with the Great option | |
|---|---|
| Situation | Outcome with the Great option |
| billing-3 restarts | P4 and P5 pause for a moment. P0 to P3 never do |
| 50 consumers restart one by one | Each restart touches the two partitions of that consumer. The other 98 keep going |
| A consumer dies without saying goodbye | The coordinator misses its heartbeats for 10 seconds and gives its partitions away |
| A partition changes owner with records in hand | The old owner commits first. Whatever was not committed is read again by the new owner |
The trade-off to name. A cooperative rebalance can take two rounds, so the final balance arrives a little later. And during the change, a partition that moves is paused while its old owner commits. Both are small next to stopping the whole group.
Because the new owner starts at the committed offset. If billing-1 has processed up to 8200 but committed only 8000, the new owner reads 8000 to 8199 again. Nothing is lost, but 200 records are processed twice. So the consumer finishes what it has in hand, commits, and only then lets go.
"Inside a group every partition has exactly one owner, and a coordinator broker manages the membership. The naive protocol is eager: on any change, all consumers revoke all partitions and rejoin, so the whole group stops for a few seconds. In a rolling deploy of 50 pods that is 100 stop-the-world pauses. I use cooperative rebalancing: consumers keep their partitions, and only the partitions that must move are revoked, in a short second round. Consumers commit before they release a partition, because the new owner resumes from the committed offset. I also give consumers static member ids, so a quick restart does not trigger a rebalance at all."
Follow-up: "How many consumers can a group usefully have?" — As many as the topic has partitions. One more than that owns nothing.
Scenario: A hot partition must take 10 MB a second, which is 10,000 records. The whole cluster takes 1 million records a second. The disks are ordinary. A disk can confirm about 1,000 writes a second when it is asked to flush each one. That confirmation is called an fsync: the program asks the operating system to really put the data on the disk, and waits.
Three ways to build it. Decide what you would do first. The answers are covered: click a card to reveal it.
The idea. Treat every record like a row in a database. One request per record. Write it, flush it to disk, answer. To serve a read, load the records into the broker and send them.
Where it breaks. This partition alone needs 10,000 requests and 10,000 flushes a second, and the disk does 1,000. So the partition tops out at a tenth of its target. Reading is wasteful too: every byte is copied four times on its way out, from the disk into the operating system's memory, into the broker's memory, into the network buffer, and onto the network card.
The idea. The producer collects records for 10 ms and sends 100 of them in one request. The broker adds the batch to the end of the file in one write.
What it fixes. Requests. The hot partition now needs 100 requests a second, not 10,000. And adding at the end of a file is the kind of write a disk is good at.
What it still misses. The broker still flushes before every ack. A broker holds 10,000 partition replicas, so even one flush per batch is far more than 1,000 a second. To make reads fast, the broker keeps recent records in its own memory. The operating system keeps the same bytes in its memory as well, so the memory is used twice, and a restart of the broker empties its copy. And every fetch still copies each byte through the broker.
The key idea. Let the operating system do what it already does well, and let replication do the job of the flush. The page cache is the memory in which the operating system keeps recently written and read parts of files.
How it works
sendfile. This system call makes the kernel move bytes from the page cache straight to the network connection. The bytes never enter the broker process. This is called zero-copy.The three designs side by side, in one picture:
Play the three options. Switch between them with the tabs at the top of the figure.
Produce(orders-0): 1 recordProducer → Broker 1Nothing is written in this step.
Swipe to see all columns
| DD4 side by side | |||
|---|---|---|---|
| Bad: per record | Good: batches | Great: page cache and zero-copy | |
| Requests a second for the hot partition | 10,000 | 100 | 100 |
| Disk flushes before an ack | One per record | One per batch | None. Three copies in memory make it safe |
Check it against the scenario
| One broker at 100 MB a second | |
|---|---|
| Situation | Outcome with the Great option |
| 10,000 records a second on one partition | 100 appends a second |
| 10,000 partition replicas on one broker | No flush on the path of an ack. The OS flushes in bulk |
| A consumer at the end of the log | Served from memory, within the 200 ms |
| The broker process restarts | The page cache belongs to the OS, so it is still warm |
| All three in-sync brokers lose power in the same second | Records not yet flushed can be lost. Put the replicas in different racks |
The trade-off to name. Safety now rests on replication, not on a flush. If all in-sync copies lose power together, the last moments of data are gone. Spreading replicas over racks makes that unlikely. And zero-copy does not work when the broker has to encrypt the bytes itself.
It is a trade. A request has fixed costs: a network round trip, a system call, an entry in the log. A batch pays them once for 100 records, at the price of up to 10 ms out of a budget of 200. The producer sends as soon as a batch is full or the time is up. A topic that needs the lowest delay can set the wait to zero.
"A million messages a second is an IO problem, and I have three levers. One, the producer batches per partition, by size or after about ten milliseconds, so the fixed cost of a request is paid once per hundred records. Two, the broker appends to the end of a segment file through the OS page cache and does not fsync before the ack. Durability comes from the in-sync replicas having the batch, and the OS flushes in the background. Three, fetches use sendfile, so bytes go from the page cache to the socket without entering the broker process. The trade-off is that a power loss on all in-sync replicas at once can lose unflushed data, so I spread replicas across racks."
Follow-up: "Why not keep a cache inside the broker?" — It would hold the same bytes as the page cache a second time, it would be lost on every restart, and a large heap means long garbage collection pauses.
| If the interviewer keeps going | |
|---|---|
| Question | Short answer |
| Can you promise exactly-once? | Inside the log, yes. The idempotent producer removes duplicate writes, and a transaction can write to several partitions and commit the consumer's offset in one step. The promise ends where a record leaves the log: a write to another system must be safe to repeat |
| One region goes down? | Run one cluster per region and copy topics between them with a mirror process. Waiting for another region on every ack would break the 200 ms. The price: the last moments before an outage may not have been copied yet |
| 1 PB on local disks is expensive | Tiered storage: move closed segments to object storage and keep only recent ones on the broker. A replay of old data is slower, and replay is not on the fast path |
| What do you monitor? | Partitions with fewer in-sync copies than replicas, how far each group is behind the end of the log, and how often in-sync sets change. Alert when a group is behind by half the retention time |
Then the broker must track every consumer, and nobody can replay. Keep a log, and let each group keep one offset per partition.
Global order needs one writer for everything, and that ends the parallel work. Promise order inside a partition, and use the key to keep related records together.
One copy dies with its machine. Acknowledge when every in-sync copy has the batch.
Then "all in-sync copies" quietly means "the leader". Set a floor of two and refuse writes below it.
A replica that is behind erases acknowledged records when it leads. Elect only from the in-sync set, and wait if it is empty.
A crash then skips records for good. Process first and commit second, and make the processing safe to repeat.
A rolling deploy becomes a hundred full stops. Move only the partitions that have to move, and give consumers fixed ids.
No disk confirms a million small writes a second. Batch, append to the page cache, and let the replicas provide the safety.
The shape of a strong answer: say that it is a log and not a queue. Split topics into partitions, with one leader each. Acknowledge a write when every in-sync copy has it, and elect leaders only from the in-sync set. Let consumers pull and move as few partitions as possible when a group changes. Explain the speed as three facts about IO: batches, the page cache, and sends without copies.
It is a log, not a queue
Records are appended and numbered. Reading removes nothing. Replay, many independent groups and cheap retention all come from that.
"Acknowledged" has one meaning
Every in-sync copy has the record. The in-sync set has a floor of two, and only its members may lead. So a new leader always has what was promised.
Keep the broker thin
Producers batch and pick the partition. Consumers pull and commit their own position. The broker appends to the end of a file and sends ranges of it without copying them.
| What the interviewer expects at each level | |
|---|---|
| Level | A strong answer shows |
| Junior | Sees that this is a stored log and not a queue that forgets. Names producers, brokers, partitions and consumer groups. Explains why order holds per partition and why retention does not depend on reading |
| Mid-level | Gets to partitions quickly as the unit of order, parallel work and replication. Explains the in-sync set and acks=all with their cost in delay. Uses offsets to explain replay and at-least-once |
| Senior | Goes to the hard parts first: the in-sync set with its floor, leader election and the unclean case, rebalancing during a rolling deploy. Tells the throughput story as an IO story and names what each choice costs |
These aren't toy problems — they reflect real infrastructure challenges at companies that move data at this scale. If you want to walk through this design in a mock interview or get feedback on your own approach, book a session with us. We're here to help you sharpen your thinking, build your confidence, and land your next offer.
Pick an answer for each question, and you see at once whether it is right. Show explanation opens the answer, why it is right, and why each of the other options fails.
Question 1 of 10
A producer uses acks=1. The leader adds the batch to its log, answers, and dies before the followers fetch. What is true?
Question 2 of 10
What does the high watermark of a partition tell you?
Question 3 of 10
The leader of a partition dies. Which replica may the controller promote?
Question 4 of 10
min.insync.replicas is 2. Two of three brokers are down, so the in-sync set is the leader alone. A producer writes with acks=all. What happens?
Question 5 of 10
A consumer has processed 60 of 100 records and crashes before it commits. What does the group see?
Question 6 of 10
When is a record deleted from a partition?
Question 7 of 10
A group uses cooperative rebalancing. One consumer leaves. Which partitions stop being processed?
Question 8 of 10
The broker does not flush to disk before it acknowledges a write. What makes the write safe?
Question 9 of 10
Two records are written to the same topic with different keys. What can a consumer rely on?
Question 10 of 10
A producer sends a batch to a broker that is no longer the leader of the partition. What should the producer do?
| DD3 | You deploy the 50 consumers of a group one by one. What happens to processing? | The group rebalances by itself | Each rebalance stops every consumer. That is 100 full stops in 8 minutes |
| DD4 | How does a broker with ordinary disks take 100 MB every second? | Faster disks and a cache in the broker | The cost is per request, per disk flush and per copy. It is not per byte |
| Partitions can be written and read in parallel. A key keeps related records together |
| When is a write acknowledged? | When it would survive the loss of one broker | The leader's own copy is not enough (DD1, DD2) |
| Push or pull? | Pull. A consumer asks for records when it is ready | The broker keeps no state per consumer. A slow reader just asks less often |
| How much? | 1 million messages a second of 1 KB, about 1 PB kept, under 200 ms end to end | The write path must be batched and sequential (DD4) |
| A replica is alive | It may become the leader | It may be far behind. Only a replica that has every acknowledged record may lead |
| A consumer received a record | The record was processed | The consumer can crash before it commits. Then the record is read again |
| Every group has read a record | The record can be deleted | A new group may want to replay it. Only the retention time deletes |
| Two records are in the same topic | They are in order | Order exists only inside one partition |
| Partitions |
| 100,000 in 10,000 topics. With three copies: 300,000 replicas, 10,000 on each broker |
| One partition | 10 KB a second on average. A hot one must take 10 MB a second: 10,000 messages |
| End to end | Under 200 ms at p99 |
| One leader per partition takes all writes |
| One machine hands out the offsets, so there is one order |
| Followers pull from the leader. The leader tracks who is in sync | A slow copy can be left behind without stopping the writes (DD2) |
| Acknowledge when every in-sync copy has the batch | An acknowledged record survives the loss of the leader (DD1) |
| A small controller quorum elects leaders | Decisions about leadership are made in one place, off the data path |
| Consumers pull, and commit their offset into an internal topic | No state per consumer on the broker, and no extra database |
| The log is cut into segment files | Old data is removed by deleting whole files |
| Batches, the page cache and zero-copy sends | The disk sees a few large sequential writes (DD4) |
| Answers: which offset is yesterday 09:00? |
| The brokers that hold a copy: 1, 2, 3 |
leader | INT | The one replica that takes writes and reads: Broker 1 |
leader_epoch | INT | Goes up by one with every new leader: 5. A broker with an older number is ignored |
isr | LIST | The in-sync replicas: the copies that have kept up with the leader. 1, 2, 3 (DD2) |
INT |
| The next offset to read: 7100. Only the newest record per key is kept |
committed_at | TIMESTAMP | When the group committed |
| Page cache | The newest part of every log, in the memory of the operating system | Disposable. It is refilled from disk |
NOT_ENOUGH_REPLICASFetch | Topic, partition, offset, max_bytes, max_wait_ms | Records, the high watermark, the log start offset. Or OFFSET_OUT_OF_RANGE |
ListOffsets | Topic, partition, a timestamp | The first offset at or after that time |
OffsetCommit / OffsetFetch | Group, topic, partition, and the offset to store | OK, or the stored offset |
JoinGroup / SyncGroup / Heartbeat | Group and member id | The partitions this member owns (DD3) |
| Phase 3: Replay and retention (FR4, FR6) |
| Green |
| A second group reads yesterday's orders. The oldest segment is deleted |
| The partition now starts at offset 2000 |
| Phase 4: Leader failover (NFR3, NFR4) | Purple | Broker 1 dies while it leads the partition | Broker 2 leads, epoch 6 |
Produceacks=all| Nothing yet |
| 3 | Broker 1 adds the batch to the end of its log. It does not answer yet. | Broker 1: offsets 7000 to 7099. Log end 7000 to 7100 |
| 4 | Brokers 2 and 3 are always asking the leader for more: Fetch(orders-0, from 7000). Each gets the batch and adds it to its own log. | Brokers 2 and 3: offsets 7000 to 7099 |
| 5 | Their next fetch asks from 7100. That tells the leader that both have everything below 7100. | High watermark 7000 to 7100 |
| 6 | Broker 1 answers the producer: base_offset 7000, the first offset of the batch. Only now is the write acknowledged. | Nothing |
orders-3| No order relative to the other two |
| order 9001 paid | user-42 | orders-0 | Always after 'order 9001 placed' |
billing-2| Group billing: who owns what |
| 2 | It asks where the group stopped: OffsetFetch(billing, orders-0). The answer is 7000. | Nothing |
| 3 | It sends Fetch(orders-0, offset 7000) to Broker 1 with max_wait_ms 500. If nothing is new, the broker holds the request and answers as soon as the high watermark moves. | Nothing |
| 4 | Broker 1 answers with offsets 7000 to 7099 and the high watermark 7100. The bytes go from the broker's memory straight to the network. | Nothing |
| 5 | billing-1 bills the 100 orders. | Whatever billing writes in its own system |
| 6 | It commits: OffsetCommit(billing, orders-0, 7100). | consumer_offsets: billing, orders, 0 is now 7100 |
| Nothing |
| 3 | Broker 1 finds the segment that holds offset 2600: seg-2000. Its index says that offset 2560 is at byte 573,440. The broker jumps there and reads 40 records forward. | Nothing |
| 4 | The records from 2600 on go to analytics-1. The group billing is not affected: every group has its own position. | Later: analytics, orders, 0 in consumer_offsets |
| 5 | A retention job runs inside the broker every 5 minutes. It looks for closed segments older than 4 days and finds seg-0. | Nothing |
| 6 | The three files of seg-0 are deleted. No consumer was asked. | Log start offset 0 to 2000 |
orders-0: leader 1 to 2, epoch 5 to 6, in-sync set 2, 3 |
| 4 | The controller tells Brokers 2 and 3. Broker 3 now fetches from Broker 2. | Nothing |
| 5 | The producer's request to Broker 1 gets no answer. It asks a live broker for Metadata(orders) and learns that Broker 2 leads. | Producer: cached leader is Broker 2 |
| 6 | The producer sends the same batch to Broker 2 and gets its ack. Consumers do the same with their fetches. | Nothing was lost: Broker 2 holds everything below the high watermark |
| DD1 |
| When is a write acknowledged? |
| The leader dies 10 ms after it took a batch |
| NFR3 — Durability |
| DD2 | A slow follower, then a dead leader | Broker 3 falls 900 records behind, then Broker 1 dies | NFR3, NFR4 — Durability, availability |
| DD3 | Deploy the consumers without stopping the group | A rolling restart of the consumers of one group | NFR2, NFR4 — Latency, availability |
| DD4 | A million messages a second on ordinary disks | A hot partition at 10,000 records a second | NFR1, NFR2 — Throughput, latency |
A producer that retries this way is called an idempotent producer: sending the same batch twice has the same effect as sending it once.
| A retry after a lost answer |
| There are no retries |
| May write the batch twice |
| Recognised by sequence number, written once |
| Added delay per batch | None | One append | One append and one follower fetch: a few milliseconds |
| It never saw the batch. Consumers read only below the high watermark |
NOT_ENOUGH_REPLICASIf no member of the in-sync set is alive, the partition waits for one to return. Promoting a replica from outside the set is called an unclean leader election. It is switched off by default, and switching it on is a deliberate decision in a disaster: it trades lost records for availability.
| Broker 1 dies at 10:05 | Safe, but hardly anything was written since 10:00 | 900 acknowledged records are lost | Broker 2 leads. Nothing is lost |
| Only one in-sync copy is left | Cannot happen: writes stop first | Writes go on with a single copy | Writes are refused until a second copy is back |
| It sees epoch 6, cuts off whatever its log has beyond the new leader's log, and becomes a follower |
billing-3 comes back. In a first round, the owners of P4 and P5 finish the records in hand, commit, and release only these two partitions.billing-3. It starts at the committed offsets.One more step removes most rebalances: give every consumer a fixed member id. A consumer that returns under the same id within the session timeout, for example 30 seconds, gets its partitions back with no rebalance at all.
| 100 full stops, about 5 of 8 minutes |
| 100 full stops, less state to rebuild |
| Each step touches 2 of 100 partitions |
| Rounds per rebalance | One | One | One or two short ones |
| Where recent records are kept in memory |
| Nowhere on purpose |
| In the broker and again in the OS |
| Only in the page cache |
| Copies of each byte on the way out | Four | Four | Two: into the page cache, then to the network card |
| A consumer is slower than the retention | Its next fetch gets OFFSET_OUT_OF_RANGE. It has to jump to the log start offset and report the gap. The alert above exists to catch this earlier |
| Can you add partitions later? | Yes, but the key to partition mapping changes, so order per key breaks at that moment. Choose the count up front: expected peak divided by 10 MB a second, with room to grow |
| One key is very hot | One key means one partition and one consumer. If its events need no order, add a random suffix to the key. If they do, that key is limited to what one partition can take |
| The controller fails? | It is a quorum of three: one can fail and the other two carry on. Meanwhile brokers serve with the leaders they know |